From 28c980a6bf8445674c01f5bf612dd953d6cabab2 Mon Sep 17 00:00:00 2001 From: fern-api <115122769+fern-api[bot]@users.noreply.github.com> Date: Thu, 7 Aug 2025 16:06:15 +0000 Subject: [PATCH] SDK regeneration --- .github/workflows/ci.yml | 6 +- build.gradle | 4 +- gradle/wrapper/gradle-wrapper.jar | Bin 43764 -> 43583 bytes gradle/wrapper/gradle-wrapper.properties | 2 +- gradlew | 9 +- gradlew.bat | 4 +- reference.md | 4735 ----------------- sample-app/src/main/java/sample/App.java | 2 +- src/main/java/com/cohere/api/AsyncCohere.java | 294 - .../com/cohere/api/AsyncCohereBuilder.java | 218 - .../java/com/cohere/api/AsyncRawCohere.java | 1694 ------ src/main/java/com/cohere/api/Cohere.java | 1047 +++- .../java/com/cohere/api/CohereBuilder.java | 178 +- src/main/java/com/cohere/api/RawCohere.java | 1264 ----- .../com/cohere/api/core/ClientOptions.java | 91 +- .../cohere/api/core/CohereApiException.java | 28 - .../cohere/api/core/CohereHttpResponse.java | 37 - .../api/core/InputStreamRequestBody.java | 7 +- .../java/com/cohere/api/core/Nullable.java | 140 - .../api/core/NullableNonemptyFilter.java | 19 - .../cohere/api/core/QueryStringMapper.java | 142 - .../com/cohere/api/core/RequestOptions.java | 37 +- .../com/cohere/api/core/RetryInterceptor.java | 2 +- src/main/java/com/cohere/api/core/Stream.java | 271 +- .../cohere/api/errors/BadRequestError.java | 6 - .../api/errors/ClientClosedRequestError.java | 6 - .../com/cohere/api/errors/ForbiddenError.java | 6 - .../api/errors/GatewayTimeoutError.java | 6 - .../api/errors/InternalServerError.java | 6 - .../cohere/api/errors/InvalidTokenError.java | 6 - .../com/cohere/api/errors/NotFoundError.java | 6 - .../api/errors/NotImplementedError.java | 6 - .../api/errors/ServiceUnavailableError.java | 6 - .../api/errors/TooManyRequestsError.java | 6 - .../cohere/api/errors/UnauthorizedError.java | 6 - .../api/errors/UnprocessableEntityError.java | 6 - .../com/cohere/api/requests/ChatRequest.java | 384 +- .../api/requests/ChatStreamRequest.java | 384 +- .../cohere/api/requests/ClassifyRequest.java | 20 - .../api/requests/DetokenizeRequest.java | 10 - .../com/cohere/api/requests/EmbedRequest.java | 26 - .../cohere/api/requests/GenerateRequest.java | 132 - .../api/requests/GenerateStreamRequest.java | 132 - .../cohere/api/requests/RerankRequest.java | 52 - .../cohere/api/requests/SummarizeRequest.java | 40 - .../cohere/api/requests/TokenizeRequest.java | 8 - .../connectors/AsyncConnectorsClient.java | 146 - .../connectors/AsyncRawConnectorsClient.java | 855 --- .../connectors/ConnectorsClient.java | 490 +- .../connectors/RawConnectorsClient.java | 624 --- .../requests/ConnectorsListRequest.java | 6 - .../ConnectorsOAuthAuthorizeRequest.java | 3 - .../requests/CreateConnectorRequest.java | 44 - .../requests/UpdateConnectorRequest.java | 15 - .../datasets/AsyncDatasetsClient.java | 114 - .../datasets/AsyncRawDatasetsClient.java | 751 --- .../resources/datasets/DatasetsClient.java | 454 +- .../resources/datasets/RawDatasetsClient.java | 559 -- .../requests/DatasetsCreateRequest.java | 243 +- .../requests/DatasetsListRequest.java | 18 - .../types/DatasetsCreateResponse.java | 3 - ...atasetsCreateResponseDatasetPartsItem.java | 180 + .../types/DatasetsGetUsageResponse.java | 3 - .../embedjobs/AsyncEmbedJobsClient.java | 87 - .../embedjobs/AsyncRawEmbedJobsClient.java | 547 -- .../resources/embedjobs/EmbedJobsClient.java | 324 +- .../embedjobs/RawEmbedJobsClient.java | 394 -- .../requests/CreateEmbedJobRequest.java | 56 - .../finetuning/AsyncFinetuningClient.java | 184 - .../finetuning/AsyncRawFinetuningClient.java | 807 --- .../finetuning/FinetuningClient.java | 452 +- .../finetuning/RawFinetuningClient.java | 619 --- .../finetuning/types/BaseModel.java | 22 - .../types/CreateFinetunedModelResponse.java | 3 - .../finetuning/finetuning/types/Event.java | 9 - .../finetuning/types/FinetunedModel.java | 56 - .../types/GetFinetunedModelResponse.java | 3 - .../finetuning/types/Hyperparameters.java | 28 - .../finetuning/types/ListEventsResponse.java | 10 - .../types/ListFinetunedModelsResponse.java | 10 - .../ListTrainingStepMetricsResponse.java | 7 - .../finetuning/finetuning/types/Settings.java | 26 - .../finetuning/types/TrainingStepMetrics.java | 9 - .../types/UpdateFinetunedModelResponse.java | 3 - .../finetuning/types/WandbConfig.java | 14 - .../requests/FinetuningListEventsRequest.java | 16 - .../FinetuningListFinetunedModelsRequest.java | 16 - ...etuningListTrainingStepMetricsRequest.java | 7 - ...FinetuningUpdateFinetunedModelRequest.java | 269 +- .../resources/models/AsyncModelsClient.java | 64 - .../models/AsyncRawModelsClient.java | 315 -- .../api/resources/models/ModelsClient.java | 188 +- .../api/resources/models/RawModelsClient.java | 234 - .../models/requests/ModelsListRequest.java | 13 - .../api/resources/v2/AsyncRawV2Client.java | 589 -- .../api/resources/v2/AsyncV2Client.java | 99 - .../cohere/api/resources/v2/RawV2Client.java | 430 -- .../com/cohere/api/resources/v2/V2Client.java | 359 +- .../resources/v2/requests/V2ChatRequest.java | 204 +- .../v2/requests/V2ChatStreamRequest.java | 204 +- .../resources/v2/requests/V2EmbedRequest.java | 70 - .../v2/requests/V2RerankRequest.java | 81 +- .../v2/types/V2ChatRequestDocumentsItem.java | 3 +- .../V2ChatStreamRequestDocumentsItem.java | 3 +- .../resources/v2/types/V2RerankResponse.java | 3 - .../v2/types/V2RerankResponseResultsItem.java | 57 +- .../V2RerankResponseResultsItemDocument.java | 110 + .../cohere/api/types/ApiMetaBilledUnits.java | 15 - .../com/cohere/api/types/ApiMetaTokens.java | 6 - .../cohere/api/types/AssistantMessage.java | 3 - .../api/types/AssistantMessageResponse.java | 3 - .../AssistantMessageResponseContentItem.java | 17 +- .../api/types/AssistantMessageV2Content.java | 3 +- .../types/AssistantMessageV2ContentItem.java | 2 - .../com/cohere/api/types/ChatCitation.java | 24 - .../types/ChatCitationGenerationEvent.java | 3 - .../com/cohere/api/types/ChatConnector.java | 26 - ...tContentDeltaEventDeltaMessageContent.java | 31 +- ...tContentStartEventDeltaMessageContent.java | 29 +- .../com/cohere/api/types/ChatDataMetrics.java | 9 - .../cohere/api/types/ChatDocumentSource.java | 3 - .../com/cohere/api/types/ChatMessage.java | 4 - .../api/types/ChatMessageEndEventDelta.java | 3 - .../api/types/ChatMessageStartEvent.java | 3 - .../ChatMessageStartEventDeltaMessage.java | 3 - .../com/cohere/api/types/ChatMessageV2.java | 5 - .../ChatRequestConnectorsSearchOptions.java | 103 + .../ChatResponseV2.java} | 69 +- .../ChatSearchQueriesGenerationEvent.java | 3 - .../com/cohere/api/types/ChatSearchQuery.java | 8 - .../cohere/api/types/ChatSearchResult.java | 22 - .../api/types/ChatSearchResultConnector.java | 4 - .../api/types/ChatSearchResultsEvent.java | 6 - .../cohere/api/types/ChatStreamEndEvent.java | 20 - .../api/types/ChatStreamStartEvent.java | 4 - .../api/types/ChatTextGenerationEvent.java | 4 - .../cohere/api/types/ChatThinkingContent.java | 102 + .../types/ChatToolCallsGenerationEvent.java | 3 - .../com/cohere/api/types/ChatToolSource.java | 3 - .../java/com/cohere/api/types/Citation.java | 40 +- .../com/cohere/api/types/CitationOptions.java | 5 - .../com/cohere/api/types/CitationType.java | 2 + .../ClassifyResponseClassificationsItem.java | 40 - .../java/com/cohere/api/types/Connector.java | 74 - .../com/cohere/api/types/ConnectorOAuth.java | 26 - .../java/com/cohere/api/types/Content.java | 3 - .../api/types/CreateConnectorOAuth.java | 15 - .../api/types/CreateConnectorServiceAuth.java | 4 - .../java/com/cohere/api/types/Dataset.java | 40 - .../com/cohere/api/types/DatasetPart.java | 44 - .../cohere/api/types/DetokenizeResponse.java | 4 - .../java/com/cohere/api/types/Document.java | 6 - .../cohere/api/types/EmbedByTypeResponse.java | 16 - .../types/EmbedByTypeResponseEmbeddings.java | 15 - .../com/cohere/api/types/EmbedContent.java | 3 - .../cohere/api/types/EmbedFloatsResponse.java | 18 - .../java/com/cohere/api/types/EmbedInput.java | 3 - .../java/com/cohere/api/types/EmbedJob.java | 36 - .../com/cohere/api/types/EmbedResponse.java | 3 - .../api/types/FinetuneDatasetMetrics.java | 18 - .../cohere/api/types/GenerateStreamError.java | 10 - .../cohere/api/types/GenerateStreamText.java | 10 - .../api/types/GenerateStreamedResponse.java | 4 - .../java/com/cohere/api/types/Generation.java | 12 - .../cohere/api/types/GetModelResponse.java | 27 - src/main/java/com/cohere/api/types/Image.java | 16 - .../java/com/cohere/api/types/ImageUrl.java | 10 - .../cohere/api/types/JsonResponseFormat.java | 14 - .../api/types/JsonResponseFormatV2.java | 14 - .../com/cohere/api/types/LabelMetric.java | 9 - .../api/types/ListConnectorsResponse.java | 3 - .../cohere/api/types/ListModelsResponse.java | 3 - .../com/cohere/api/types/LogprobItem.java | 9 - .../java/com/cohere/api/types/Message.java | 5 - .../java/com/cohere/api/types/Metrics.java | 33 +- .../cohere/api/types/MetricsEmbedData.java | 100 + .../api/types/MetricsEmbedDataFieldsItem.java | 124 + .../api/types/NonStreamedChatResponse.java | 91 +- .../api/types/OAuthAuthorizeResponse.java | 3 - .../api/types/RerankRequestDocumentsItem.java | 3 +- .../com/cohere/api/types/RerankResponse.java | 3 - .../api/types/RerankResponseResultsItem.java | 14 - .../RerankResponseResultsItemDocument.java | 4 - .../cohere/api/types/RerankerDataMetrics.java | 18 - .../com/cohere/api/types/ResponseFormat.java | 3 - .../cohere/api/types/ResponseFormatV2.java | 3 - .../cohere/api/types/SingleGeneration.java | 12 - .../api/types/SingleGenerationInStream.java | 10 - .../java/com/cohere/api/types/Source.java | 3 - .../api/types/StreamedChatResponse.java | 10 - .../StreamedChatResponseV2.java} | 107 +- .../cohere/api/types/SummarizeResponse.java | 6 - .../api/types/SystemMessageV2Content.java | 3 +- .../api/types/SystemMessageV2ContentItem.java | 2 - .../java/com/cohere/api/types/Thinking.java | 141 + ...ReasoningEffort.java => ThinkingType.java} | 10 +- .../cohere/api/types/TokenizeResponse.java | 3 - src/main/java/com/cohere/api/types/Tool.java | 30 - .../java/com/cohere/api/types/ToolCall.java | 10 - .../com/cohere/api/types/ToolCallDelta.java | 12 - .../com/cohere/api/types/ToolContent.java | 3 - .../com/cohere/api/types/ToolMessageV2.java | 8 - .../api/types/ToolMessageV2Content.java | 3 +- .../types/ToolParameterDefinitionsValue.java | 16 - .../java/com/cohere/api/types/ToolV2.java | 3 - .../com/cohere/api/types/ToolV2Function.java | 16 - .../cohere/api/types/TruncationStrategy.java | 200 + .../TruncationStrategyAutoPreserveOrder.java | 59 + .../api/types/TruncationStrategyNone.java | 59 + .../cohere/api/types/UsageBilledUnits.java | 12 - .../com/cohere/api/types/UsageTokens.java | 6 - .../com/cohere/api/types/UserMessageV2.java | 6 - .../api/types/UserMessageV2Content.java | 3 +- src/test/java/com/cohere/api/StreamTest.java | 86 - .../api/core/QueryStringMapperTest.java | 339 -- 215 files changed, 5436 insertions(+), 20248 deletions(-) delete mode 100644 reference.md delete mode 100644 src/main/java/com/cohere/api/AsyncCohere.java delete mode 100644 src/main/java/com/cohere/api/AsyncCohereBuilder.java delete mode 100644 src/main/java/com/cohere/api/AsyncRawCohere.java delete mode 100644 src/main/java/com/cohere/api/RawCohere.java delete mode 100644 src/main/java/com/cohere/api/core/CohereHttpResponse.java delete mode 100644 src/main/java/com/cohere/api/core/Nullable.java delete mode 100644 src/main/java/com/cohere/api/core/NullableNonemptyFilter.java delete mode 100644 src/main/java/com/cohere/api/core/QueryStringMapper.java delete mode 100644 src/main/java/com/cohere/api/resources/connectors/AsyncConnectorsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/connectors/AsyncRawConnectorsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/connectors/RawConnectorsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/datasets/AsyncDatasetsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/datasets/AsyncRawDatasetsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/datasets/RawDatasetsClient.java create mode 100644 src/main/java/com/cohere/api/resources/datasets/types/DatasetsCreateResponseDatasetPartsItem.java delete mode 100644 src/main/java/com/cohere/api/resources/embedjobs/AsyncEmbedJobsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/embedjobs/AsyncRawEmbedJobsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/embedjobs/RawEmbedJobsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/finetuning/AsyncFinetuningClient.java delete mode 100644 src/main/java/com/cohere/api/resources/finetuning/AsyncRawFinetuningClient.java delete mode 100644 src/main/java/com/cohere/api/resources/finetuning/RawFinetuningClient.java delete mode 100644 src/main/java/com/cohere/api/resources/models/AsyncModelsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/models/AsyncRawModelsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/models/RawModelsClient.java delete mode 100644 src/main/java/com/cohere/api/resources/v2/AsyncRawV2Client.java delete mode 100644 src/main/java/com/cohere/api/resources/v2/AsyncV2Client.java delete mode 100644 src/main/java/com/cohere/api/resources/v2/RawV2Client.java create mode 100644 src/main/java/com/cohere/api/resources/v2/types/V2RerankResponseResultsItemDocument.java create mode 100644 src/main/java/com/cohere/api/types/ChatRequestConnectorsSearchOptions.java rename src/main/java/com/cohere/api/{resources/v2/types/V2ChatResponse.java => types/ChatResponseV2.java} (76%) create mode 100644 src/main/java/com/cohere/api/types/ChatThinkingContent.java create mode 100644 src/main/java/com/cohere/api/types/MetricsEmbedData.java create mode 100644 src/main/java/com/cohere/api/types/MetricsEmbedDataFieldsItem.java rename src/main/java/com/cohere/api/{resources/v2/types/V2ChatStreamResponse.java => types/StreamedChatResponseV2.java} (84%) create mode 100644 src/main/java/com/cohere/api/types/Thinking.java rename src/main/java/com/cohere/api/types/{ReasoningEffort.java => ThinkingType.java} (72%) create mode 100644 src/main/java/com/cohere/api/types/TruncationStrategy.java create mode 100644 src/main/java/com/cohere/api/types/TruncationStrategyAutoPreserveOrder.java create mode 100644 src/main/java/com/cohere/api/types/TruncationStrategyNone.java delete mode 100644 src/test/java/com/cohere/api/StreamTest.java delete mode 100644 src/test/java/com/cohere/api/core/QueryStringMapperTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d868be..1fbf230 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,7 +8,7 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v3 - name: Set up Java id: setup-jre @@ -25,7 +25,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v3 - name: Set up Java id: setup-jre @@ -43,7 +43,7 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v4 + uses: actions/checkout@v3 - name: Set up Java id: setup-jre diff --git a/build.gradle b/build.gradle index 102bc1e..d94c1ff 100644 --- a/build.gradle +++ b/build.gradle @@ -46,7 +46,7 @@ java { group = 'com.cohere' -version = '1.8.0' +version = '0.0.1' jar { dependsOn(":generatePomFileForMavenPublication") @@ -77,7 +77,7 @@ publishing { maven(MavenPublication) { groupId = 'com.cohere' artifactId = 'cohere-java' - version = '1.8.0' + version = '0.0.1' from components.java pom { name = 'cohere' diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 1b33c55baabb587c669f562ae36f953de2481846..a4b76b9530d66f5e68d973ea569d8e19de379189 100644 GIT binary patch delta 34959 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

Gn4F+B~IivciU9^t0j-Mgao3 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 DDw4oP delta 34943 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 Rh /dev/null && printf '%s\n' "$PWD" ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -114,7 +115,7 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH="\\\"\\\"" +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -205,7 +206,7 @@ fi DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. @@ -213,7 +214,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ - -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. diff --git a/gradlew.bat b/gradlew.bat index 5eed7ee..9b42019 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -70,11 +70,11 @@ goto fail :execute @rem Setup the command line -set CLASSPATH= +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell diff --git a/reference.md b/reference.md deleted file mode 100644 index fb5cb69..0000000 --- a/reference.md +++ /dev/null @@ -1,4735 +0,0 @@ -# Reference -

client.chatStream(request) -> Optional<StreamedChatResponse> -
-
- -#### 📝 Description - -
-
- -
-
- -Generates a streamed text response to a user message. - -To learn how to use the Chat API and RAG follow our [Text Generation guides](https://docs.cohere.com/docs/chat-api). -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.chatStream( - ChatStreamRequest - .builder() - .message("hello world!") - .stream(true) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**accepts:** `Optional` — Pass text/event-stream to receive the streamed response as server-sent events. The default is `\n` delimited events. - -
-
- -
-
- -**message:** `String` - -Text input for the model to respond to. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**model:** `Optional` - -The name of a compatible [Cohere model](https://docs.cohere.com/docs/models) or the ID of a [fine-tuned](https://docs.cohere.com/docs/chat-fine-tuning) model. - -Compatible Deployments: Cohere Platform, Private Deployments - -
-
- -
-
- -**stream:** `Boolean` - -Defaults to `false`. - -When `true`, the response will be a JSON stream of events. The final event will contain the complete response, and will have an `event_type` of `"stream-end"`. - -Streaming is beneficial for user interfaces that render the contents of the response piece by piece, as it gets generated. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**preamble:** `Optional` - -When specified, the default Cohere preamble will be replaced with the provided one. Preambles are a part of the prompt used to adjust the model's overall behavior and conversation style, and use the `SYSTEM` role. - -The `SYSTEM` role is also used for the contents of the optional `chat_history=` parameter. When used with the `chat_history=` parameter it adds content throughout a conversation. Conversely, when used with the `preamble=` parameter it adds content at the start of the conversation only. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**chatHistory:** `Optional>` - -A list of previous messages between the user and the model, giving the model conversational context for responding to the user's `message`. - -Each item represents a single message in the chat history, excluding the current user turn. It has two properties: `role` and `message`. The `role` identifies the sender (`CHATBOT`, `SYSTEM`, or `USER`), while the `message` contains the text content. - -The chat_history parameter should not be used for `SYSTEM` messages in most cases. Instead, to add a `SYSTEM` role message at the beginning of a conversation, the `preamble` parameter should be used. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**conversationId:** `Optional` - -An alternative to `chat_history`. - -Providing a `conversation_id` creates or resumes a persisted conversation with the specified ID. The ID can be any non empty string. - -Compatible Deployments: Cohere Platform - -
-
- -
-
- -**promptTruncation:** `Optional` - -Defaults to `AUTO` when `connectors` are specified and `OFF` in all other cases. - -Dictates how the prompt will be constructed. - -With `prompt_truncation` set to "AUTO", some elements from `chat_history` and `documents` will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be changed and ranked by relevance. - -With `prompt_truncation` set to "AUTO_PRESERVE_ORDER", some elements from `chat_history` and `documents` will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be preserved as they are inputted into the API. - -With `prompt_truncation` set to "OFF", no elements will be dropped. If the sum of the inputs exceeds the model's context length limit, a `TooManyTokens` error will be returned. - -Compatible Deployments: - - AUTO: Cohere Platform Only - - AUTO_PRESERVE_ORDER: Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**connectors:** `Optional>` - -Accepts `{"id": "web-search"}`, and/or the `"id"` for a custom [connector](https://docs.cohere.com/docs/connectors), if you've [created](https://docs.cohere.com/v1/docs/creating-and-deploying-a-connector) one. - -When specified, the model's reply will be enriched with information found by querying each of the connectors (RAG). - -Compatible Deployments: Cohere Platform - -
-
- -
-
- -**searchQueriesOnly:** `Optional` - -Defaults to `false`. - -When `true`, the response will only contain a list of generated search queries, but no search will take place, and no reply from the model to the user's `message` will be generated. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**documents:** `Optional>>` - -A list of relevant documents that the model can cite to generate a more accurate reply. Each document is a string-string dictionary. - -Example: -``` -[ - { "title": "Tall penguins", "text": "Emperor penguins are the tallest." }, - { "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica." }, -] -``` - -Keys and values from each document will be serialized to a string and passed to the model. The resulting generation will include citations that reference some of these documents. - -Some suggested keys are "text", "author", and "date". For better generation quality, it is recommended to keep the total word count of the strings in the dictionary to under 300 words. - -An `id` field (string) can be optionally supplied to identify the document in the citations. This field will not be passed to the model. - -An `_excludes` field (array of strings) can be optionally supplied to omit some key-value pairs from being shown to the model. The omitted fields will still show up in the citation object. The "_excludes" field will not be passed to the model. - -See ['Document Mode'](https://docs.cohere.com/docs/retrieval-augmented-generation-rag#document-mode) in the guide for more information. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**citationQuality:** `Optional` - -Defaults to `"accurate"`. - -Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want `"accurate"` results, `"fast"` results or no results. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**temperature:** `Optional` - -Defaults to `0.3`. - -A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations. - -Randomness can be further maximized by increasing the value of the `p` parameter. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**maxTokens:** `Optional` - -The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**maxInputTokens:** `Optional` - -The maximum number of input tokens to send to the model. If not specified, `max_input_tokens` is the model's context length limit minus a small buffer. - -Input will be truncated according to the `prompt_truncation` parameter. - -Compatible Deployments: Cohere Platform - -
-
- -
-
- -**k:** `Optional` - -Ensures only the top `k` most likely tokens are considered for generation at each step. -Defaults to `0`, min value of `0`, max value of `500`. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**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`. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**seed:** `Optional` - -If specified, the backend will make a best effort to sample tokens -deterministically, such that repeated requests with the same -seed and parameters should return the same result. However, -determinism cannot be totally guaranteed. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**stopSequences:** `Optional>` - -A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**frequencyPenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. - -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. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**presencePenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. - -Used to reduce repetitiveness of generated tokens. Similar to `frequency_penalty`, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**tools:** `Optional>` - -A list of available tools (functions) that the model may suggest invoking before producing a text response. - -When `tools` is passed (without `tool_results`), the `text` field in the response will be `""` and the `tool_calls` field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the `tool_calls` array will be empty. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**toolResults:** `Optional>` - -A list of results from invoking tools recommended by the model in the previous chat turn. Results are used to produce a text response and will be referenced in citations. When using `tool_results`, `tools` must be passed as well. -Each tool_result contains information about how it was invoked, as well as a list of outputs in the form of dictionaries. - -**Note**: `outputs` must be a list of objects. If your tool returns a single object (eg `{"status": 200}`), make sure to wrap it in a list. -``` -tool_results = [ - { - "call": { - "name": , - "parameters": { - : - } - }, - "outputs": [{ - : - }] - }, - ... -] -``` -**Note**: Chat calls with `tool_results` should not be included in the Chat history to avoid duplication of the message text. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**forceSingleStep:** `Optional` — Forces the chat to be single step. Defaults to `false`. - -
-
- -
-
- -**responseFormat:** `Optional` - -
-
- -
-
- -**safetyMode:** `Optional` - -Used to select the [safety instruction](https://docs.cohere.com/docs/safety-modes) inserted into the prompt. Defaults to `CONTEXTUAL`. -When `NONE` is specified, the safety instruction will be omitted. - -Safety modes are not yet configurable in combination with `tools`, `tool_results` and `documents` parameters. - -**Note**: This parameter is only compatible newer Cohere models, starting with [Command R 08-2024](https://docs.cohere.com/docs/command-r#august-2024-release) and [Command R+ 08-2024](https://docs.cohere.com/docs/command-r-plus#august-2024-release). - -**Note**: `command-r7b-12-2024` and newer models only support `"CONTEXTUAL"` and `"STRICT"` modes. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
-
-
- - -
-
-
- -
client.chat(request) -> NonStreamedChatResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Generates a text response to a user message. -To learn how to use the Chat API and RAG follow our [Text Generation guides](https://docs.cohere.com/docs/chat-api). -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.chatStream( - ChatStreamRequest - .builder() - .message("What year was he born?") - .stream(false) - .chatHistory( - new ArrayList( - Arrays.asList( - Message.user( - ChatMessage - .builder() - .message("Who discovered gravity?") - .build() - ), - Message.chatbot( - ChatMessage - .builder() - .message("The man who is widely credited with discovering gravity is Sir Isaac Newton") - .build() - ) - ) - ) - ) - .connectors( - new ArrayList( - Arrays.asList( - ChatConnector - .builder() - .id("web-search") - .build() - ) - ) - ) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**accepts:** `Optional` — Pass text/event-stream to receive the streamed response as server-sent events. The default is `\n` delimited events. - -
-
- -
-
- -**message:** `String` - -Text input for the model to respond to. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**model:** `Optional` - -The name of a compatible [Cohere model](https://docs.cohere.com/docs/models) or the ID of a [fine-tuned](https://docs.cohere.com/docs/chat-fine-tuning) model. - -Compatible Deployments: Cohere Platform, Private Deployments - -
-
- -
-
- -**stream:** `Boolean` - -Defaults to `false`. - -When `true`, the response will be a JSON stream of events. The final event will contain the complete response, and will have an `event_type` of `"stream-end"`. - -Streaming is beneficial for user interfaces that render the contents of the response piece by piece, as it gets generated. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**preamble:** `Optional` - -When specified, the default Cohere preamble will be replaced with the provided one. Preambles are a part of the prompt used to adjust the model's overall behavior and conversation style, and use the `SYSTEM` role. - -The `SYSTEM` role is also used for the contents of the optional `chat_history=` parameter. When used with the `chat_history=` parameter it adds content throughout a conversation. Conversely, when used with the `preamble=` parameter it adds content at the start of the conversation only. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**chatHistory:** `Optional>` - -A list of previous messages between the user and the model, giving the model conversational context for responding to the user's `message`. - -Each item represents a single message in the chat history, excluding the current user turn. It has two properties: `role` and `message`. The `role` identifies the sender (`CHATBOT`, `SYSTEM`, or `USER`), while the `message` contains the text content. - -The chat_history parameter should not be used for `SYSTEM` messages in most cases. Instead, to add a `SYSTEM` role message at the beginning of a conversation, the `preamble` parameter should be used. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**conversationId:** `Optional` - -An alternative to `chat_history`. - -Providing a `conversation_id` creates or resumes a persisted conversation with the specified ID. The ID can be any non empty string. - -Compatible Deployments: Cohere Platform - -
-
- -
-
- -**promptTruncation:** `Optional` - -Defaults to `AUTO` when `connectors` are specified and `OFF` in all other cases. - -Dictates how the prompt will be constructed. - -With `prompt_truncation` set to "AUTO", some elements from `chat_history` and `documents` will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be changed and ranked by relevance. - -With `prompt_truncation` set to "AUTO_PRESERVE_ORDER", some elements from `chat_history` and `documents` will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be preserved as they are inputted into the API. - -With `prompt_truncation` set to "OFF", no elements will be dropped. If the sum of the inputs exceeds the model's context length limit, a `TooManyTokens` error will be returned. - -Compatible Deployments: - - AUTO: Cohere Platform Only - - AUTO_PRESERVE_ORDER: Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**connectors:** `Optional>` - -Accepts `{"id": "web-search"}`, and/or the `"id"` for a custom [connector](https://docs.cohere.com/docs/connectors), if you've [created](https://docs.cohere.com/v1/docs/creating-and-deploying-a-connector) one. - -When specified, the model's reply will be enriched with information found by querying each of the connectors (RAG). - -Compatible Deployments: Cohere Platform - -
-
- -
-
- -**searchQueriesOnly:** `Optional` - -Defaults to `false`. - -When `true`, the response will only contain a list of generated search queries, but no search will take place, and no reply from the model to the user's `message` will be generated. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**documents:** `Optional>>` - -A list of relevant documents that the model can cite to generate a more accurate reply. Each document is a string-string dictionary. - -Example: -``` -[ - { "title": "Tall penguins", "text": "Emperor penguins are the tallest." }, - { "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica." }, -] -``` - -Keys and values from each document will be serialized to a string and passed to the model. The resulting generation will include citations that reference some of these documents. - -Some suggested keys are "text", "author", and "date". For better generation quality, it is recommended to keep the total word count of the strings in the dictionary to under 300 words. - -An `id` field (string) can be optionally supplied to identify the document in the citations. This field will not be passed to the model. - -An `_excludes` field (array of strings) can be optionally supplied to omit some key-value pairs from being shown to the model. The omitted fields will still show up in the citation object. The "_excludes" field will not be passed to the model. - -See ['Document Mode'](https://docs.cohere.com/docs/retrieval-augmented-generation-rag#document-mode) in the guide for more information. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**citationQuality:** `Optional` - -Defaults to `"accurate"`. - -Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want `"accurate"` results, `"fast"` results or no results. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**temperature:** `Optional` - -Defaults to `0.3`. - -A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations. - -Randomness can be further maximized by increasing the value of the `p` parameter. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**maxTokens:** `Optional` - -The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**maxInputTokens:** `Optional` - -The maximum number of input tokens to send to the model. If not specified, `max_input_tokens` is the model's context length limit minus a small buffer. - -Input will be truncated according to the `prompt_truncation` parameter. - -Compatible Deployments: Cohere Platform - -
-
- -
-
- -**k:** `Optional` - -Ensures only the top `k` most likely tokens are considered for generation at each step. -Defaults to `0`, min value of `0`, max value of `500`. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**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`. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**seed:** `Optional` - -If specified, the backend will make a best effort to sample tokens -deterministically, such that repeated requests with the same -seed and parameters should return the same result. However, -determinism cannot be totally guaranteed. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**stopSequences:** `Optional>` - -A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**frequencyPenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. - -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. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**presencePenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. - -Used to reduce repetitiveness of generated tokens. Similar to `frequency_penalty`, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**tools:** `Optional>` - -A list of available tools (functions) that the model may suggest invoking before producing a text response. - -When `tools` is passed (without `tool_results`), the `text` field in the response will be `""` and the `tool_calls` field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the `tool_calls` array will be empty. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**toolResults:** `Optional>` - -A list of results from invoking tools recommended by the model in the previous chat turn. Results are used to produce a text response and will be referenced in citations. When using `tool_results`, `tools` must be passed as well. -Each tool_result contains information about how it was invoked, as well as a list of outputs in the form of dictionaries. - -**Note**: `outputs` must be a list of objects. If your tool returns a single object (eg `{"status": 200}`), make sure to wrap it in a list. -``` -tool_results = [ - { - "call": { - "name": , - "parameters": { - : - } - }, - "outputs": [{ - : - }] - }, - ... -] -``` -**Note**: Chat calls with `tool_results` should not be included in the Chat history to avoid duplication of the message text. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**forceSingleStep:** `Optional` — Forces the chat to be single step. Defaults to `false`. - -
-
- -
-
- -**responseFormat:** `Optional` - -
-
- -
-
- -**safetyMode:** `Optional` - -Used to select the [safety instruction](https://docs.cohere.com/docs/safety-modes) inserted into the prompt. Defaults to `CONTEXTUAL`. -When `NONE` is specified, the safety instruction will be omitted. - -Safety modes are not yet configurable in combination with `tools`, `tool_results` and `documents` parameters. - -**Note**: This parameter is only compatible newer Cohere models, starting with [Command R 08-2024](https://docs.cohere.com/docs/command-r#august-2024-release) and [Command R+ 08-2024](https://docs.cohere.com/docs/command-r-plus#august-2024-release). - -**Note**: `command-r7b-12-2024` and newer models only support `"CONTEXTUAL"` and `"STRICT"` modes. - -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
-
-
- - -
-
-
- -
client.generateStream(request) -> Optional<GenerateStreamedResponse> -
-
- -#### 📝 Description - -
-
- -
-
- - -This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat with Streaming API. - -Generates realistic text conditioned on a given input. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.generateStream( - GenerateStreamRequest - .builder() - .prompt("Please explain to me how LLMs work") - .stream(true) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**prompt:** `String` - -The input text that serves as the starting point for generating the response. -Note: The prompt will be pre-processed and modified before reaching the model. - -
-
- -
-
- -**model:** `Optional` - -The identifier of the model to generate with. Currently available models are `command` (default), `command-nightly` (experimental), `command-light`, and `command-light-nightly` (experimental). -Smaller, "light" models are faster, while larger models will perform better. [Custom models](https://docs.cohere.com/docs/training-custom-models) can also be supplied with their full ID. - -
-
- -
-
- -**numGenerations:** `Optional` — The maximum number of generations that will be returned. Defaults to `1`, min value of `1`, max value of `5`. - -
-
- -
-
- -**stream:** `Boolean` - -When `true`, the response will be a JSON stream of events. Streaming is beneficial for user interfaces that render the contents of the response piece by piece, as it gets generated. - -The final event will contain the complete response, and will contain an `is_finished` field set to `true`. The event will also contain a `finish_reason`, which can be one of the following: -- `COMPLETE` - the model sent back a finished reply -- `MAX_TOKENS` - the reply was cut off because the model reached the maximum number of tokens for its context length -- `ERROR` - something went wrong when generating the reply -- `ERROR_TOXIC` - the model generated a reply that was deemed toxic - -
-
- -
-
- -**maxTokens:** `Optional` - -The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations. - -This parameter is off by default, and if it's not specified, the model will continue generating until it emits an EOS completion token. See [BPE Tokens](/bpe-tokens-wiki) for more details. - -Can only be set to `0` if `return_likelihoods` is set to `ALL` to get the likelihood of the prompt. - -
-
- -
-
- -**truncate:** `Optional` - -One of `NONE|START|END` to specify how the API will handle inputs longer than the maximum token length. - -Passing `START` will discard the start of the input. `END` will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. - -If `NONE` is selected, when the input exceeds the maximum input token length an error will be returned. - -
-
- -
-
- -**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`. - -
-
- -
-
- -**seed:** `Optional` - -If specified, the backend will make a best effort to sample tokens -deterministically, such that repeated requests with the same -seed and parameters should return the same result. However, -determinism cannot be totally guaranteed. -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**preset:** `Optional` - -Identifier of a custom preset. A preset is a combination of parameters, such as prompt, temperature etc. You can create presets in the [playground](https://dashboard.cohere.com/playground/generate). -When a preset is specified, the `prompt` parameter becomes optional, and any included parameters will override the preset's parameters. - -
-
- -
-
- -**endSequences:** `Optional>` — The generated text will be cut at the beginning of the earliest occurrence of an end sequence. The sequence will be excluded from the text. - -
-
- -
-
- -**stopSequences:** `Optional>` — The generated text will be cut at the end of the earliest occurrence of a stop sequence. The sequence will be included the text. - -
-
- -
-
- -**k:** `Optional` - -Ensures only the top `k` most likely tokens are considered for generation at each step. -Defaults to `0`, min value of `0`, max value of `500`. - -
-
- -
-
- -**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`. - -
-
- -
-
- -**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. - -Using `frequency_penalty` in combination with `presence_penalty` is not supported on newer models. - -
-
- -
-
- -**presencePenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. - -Can be used to reduce repetitiveness of generated tokens. Similar to `frequency_penalty`, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies. - -Using `frequency_penalty` in combination with `presence_penalty` is not supported on newer models. - -
-
- -
-
- -**returnLikelihoods:** `Optional` - -One of `GENERATION|NONE` to specify how and if the token likelihoods are returned with the response. Defaults to `NONE`. - -If `GENERATION` is selected, the token likelihoods will only be provided for generated text. - -WARNING: `ALL` is deprecated, and will be removed in a future release. - -
-
- -
-
- -**rawPrompting:** `Optional` — When enabled, the user's prompt will be sent to the model without any pre-processing. - -
-
-
-
- - -
-
-
- -
client.generate(request) -> Generation -
-
- -#### 📝 Description - -
-
- -
-
- - -This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - -Generates realistic text conditioned on a given input. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.generateStream( - GenerateStreamRequest - .builder() - .prompt("Please explain to me how LLMs work") - .stream(false) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**prompt:** `String` - -The input text that serves as the starting point for generating the response. -Note: The prompt will be pre-processed and modified before reaching the model. - -
-
- -
-
- -**model:** `Optional` - -The identifier of the model to generate with. Currently available models are `command` (default), `command-nightly` (experimental), `command-light`, and `command-light-nightly` (experimental). -Smaller, "light" models are faster, while larger models will perform better. [Custom models](https://docs.cohere.com/docs/training-custom-models) can also be supplied with their full ID. - -
-
- -
-
- -**numGenerations:** `Optional` — The maximum number of generations that will be returned. Defaults to `1`, min value of `1`, max value of `5`. - -
-
- -
-
- -**stream:** `Boolean` - -When `true`, the response will be a JSON stream of events. Streaming is beneficial for user interfaces that render the contents of the response piece by piece, as it gets generated. - -The final event will contain the complete response, and will contain an `is_finished` field set to `true`. The event will also contain a `finish_reason`, which can be one of the following: -- `COMPLETE` - the model sent back a finished reply -- `MAX_TOKENS` - the reply was cut off because the model reached the maximum number of tokens for its context length -- `ERROR` - something went wrong when generating the reply -- `ERROR_TOXIC` - the model generated a reply that was deemed toxic - -
-
- -
-
- -**maxTokens:** `Optional` - -The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations. - -This parameter is off by default, and if it's not specified, the model will continue generating until it emits an EOS completion token. See [BPE Tokens](/bpe-tokens-wiki) for more details. - -Can only be set to `0` if `return_likelihoods` is set to `ALL` to get the likelihood of the prompt. - -
-
- -
-
- -**truncate:** `Optional` - -One of `NONE|START|END` to specify how the API will handle inputs longer than the maximum token length. - -Passing `START` will discard the start of the input. `END` will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. - -If `NONE` is selected, when the input exceeds the maximum input token length an error will be returned. - -
-
- -
-
- -**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`. - -
-
- -
-
- -**seed:** `Optional` - -If specified, the backend will make a best effort to sample tokens -deterministically, such that repeated requests with the same -seed and parameters should return the same result. However, -determinism cannot be totally guaranteed. -Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments - -
-
- -
-
- -**preset:** `Optional` - -Identifier of a custom preset. A preset is a combination of parameters, such as prompt, temperature etc. You can create presets in the [playground](https://dashboard.cohere.com/playground/generate). -When a preset is specified, the `prompt` parameter becomes optional, and any included parameters will override the preset's parameters. - -
-
- -
-
- -**endSequences:** `Optional>` — The generated text will be cut at the beginning of the earliest occurrence of an end sequence. The sequence will be excluded from the text. - -
-
- -
-
- -**stopSequences:** `Optional>` — The generated text will be cut at the end of the earliest occurrence of a stop sequence. The sequence will be included the text. - -
-
- -
-
- -**k:** `Optional` - -Ensures only the top `k` most likely tokens are considered for generation at each step. -Defaults to `0`, min value of `0`, max value of `500`. - -
-
- -
-
- -**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`. - -
-
- -
-
- -**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. - -Using `frequency_penalty` in combination with `presence_penalty` is not supported on newer models. - -
-
- -
-
- -**presencePenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. - -Can be used to reduce repetitiveness of generated tokens. Similar to `frequency_penalty`, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies. - -Using `frequency_penalty` in combination with `presence_penalty` is not supported on newer models. - -
-
- -
-
- -**returnLikelihoods:** `Optional` - -One of `GENERATION|NONE` to specify how and if the token likelihoods are returned with the response. Defaults to `NONE`. - -If `GENERATION` is selected, the token likelihoods will only be provided for generated text. - -WARNING: `ALL` is deprecated, and will be removed in a future release. - -
-
- -
-
- -**rawPrompting:** `Optional` — When enabled, the user's prompt will be sent to the model without any pre-processing. - -
-
-
-
- - -
-
-
- -
client.embed(request) -> EmbedResponse -
-
- -#### 📝 Description - -
-
- -
-
- -This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - -Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page. - -If you want to learn more how to use the embedding model, have a look at the [Semantic Search Guide](https://docs.cohere.com/docs/semantic-search). -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.embed( - EmbedRequest - .builder() - .texts( - new ArrayList( - Arrays.asList("hello", "goodbye") - ) - ) - .model("embed-v4.0") - .inputType(EmbedInputType.CLASSIFICATION) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**texts:** `Optional>` — An array of strings for the model to embed. Maximum number of texts per call is `96`. - -
-
- -
-
- -**images:** `Optional>` - -An array of image data URIs for the model to embed. Maximum number of images per call is `1`. - -The image must be a valid [data URI](https://developer.mozilla.org/en-US/docs/Web/URI/Schemes/data). The image must be in either `image/jpeg` or `image/png` format and has a maximum size of 5MB. - -Images are only supported with Embed v3.0 and newer models. - -
-
- -
-
- -**model:** `Optional` — ID of one of the available [Embedding models](https://docs.cohere.com/docs/cohere-embed). - -
-
- -
-
- -**inputType:** `Optional` - -
-
- -
-
- -**embeddingTypes:** `Optional>` - -Specifies the types of embeddings you want to get back. Not required and default is None, which returns the Embed Floats response type. Can be one or more of the following types. - -* `"float"`: Use this when you want to get back the default float embeddings. Supported with all Embed models. -* `"int8"`: Use this when you want to get back signed int8 embeddings. Supported with Embed v3.0 and newer Embed models. -* `"uint8"`: Use this when you want to get back unsigned int8 embeddings. Supported with Embed v3.0 and newer Embed models. -* `"binary"`: Use this when you want to get back signed binary embeddings. Supported with Embed v3.0 and newer Embed models. -* `"ubinary"`: Use this when you want to get back unsigned binary embeddings. Supported with Embed v3.0 and newer Embed models. - -
-
- -
-
- -**truncate:** `Optional` - -One of `NONE|START|END` to specify how the API will handle inputs longer than the maximum token length. - -Passing `START` will discard the start of the input. `END` will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. - -If `NONE` is selected, when the input exceeds the maximum input token length an error will be returned. - -
-
-
-
- - -
-
-
- -
client.rerank(request) -> RerankResponse -
-
- -#### 📝 Description - -
-
- -
-
- -This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.rerank( - RerankRequest - .builder() - .documents( - new ArrayList( - Arrays.asList( - RerankRequestDocumentsItem.of(), - RerankRequestDocumentsItem.of(), - RerankRequestDocumentsItem.of(), - RerankRequestDocumentsItem.of(), - RerankRequestDocumentsItem.of() - ) - ) - ) - .query("What is the capital of the United States?") - .topN(3) - .model("rerank-v3.5") - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**model:** `Optional` — The identifier of the model to use, eg `rerank-v3.5`. - -
-
- -
-
- -**query:** `String` — The search query - -
-
- -
-
- -**documents:** `List` - -A list of document objects or strings to rerank. -If a document is provided the text fields is required and all other fields will be preserved in the response. - -The total max chunks (length of documents * max_chunks_per_doc) must be less than 10000. - -We recommend a maximum of 1,000 documents for optimal endpoint performance. - -
-
- -
-
- -**topN:** `Optional` — The number of most relevant documents or indices to return, defaults to the length of the documents - -
-
- -
-
- -**rankFields:** `Optional>` — If a JSON object is provided, you can specify which keys you would like to have considered for reranking. The model will rerank based on order of the fields passed in (i.e. rank_fields=['title','author','text'] will rerank using the values in title, author, text sequentially. If the length of title, author, and text exceeds the context length of the model, the chunking will not re-consider earlier fields). If not provided, the model will use the default text field for ranking. - -
-
- -
-
- -**returnDocuments:** `Optional` - -- If false, returns results without the doc text - the api will return a list of {index, relevance score} where index is inferred from the list passed into the request. -- If true, returns results with the doc text passed in - the api will return an ordered list of {index, text, relevance score} where index + text refers to the list passed into the request. - -
-
- -
-
- -**maxChunksPerDoc:** `Optional` — The maximum number of chunks to produce internally from a document - -
-
-
-
- - -
-
-
- -
client.classify(request) -> ClassifyResponse -
-
- -#### 📝 Description - -
-
- -
-
- -This endpoint makes a prediction about which label fits the specified text inputs best. To make a prediction, Classify uses the provided `examples` of text + label pairs as a reference. -Note: [Fine-tuned models](https://docs.cohere.com/docs/classify-fine-tuning) trained on classification examples don't require the `examples` parameter to be passed in explicitly. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.classify( - ClassifyRequest - .builder() - .inputs( - new ArrayList( - Arrays.asList("Confirm your email address", "hey i need u to send some $") - ) - ) - .examples( - new ArrayList( - Arrays.asList( - ClassifyExample - .builder() - .text("Dermatologists don't like her!") - .label("Spam") - .build(), - ClassifyExample - .builder() - .text("'Hello, open to this?'") - .label("Spam") - .build(), - ClassifyExample - .builder() - .text("I need help please wire me $1000 right now") - .label("Spam") - .build(), - ClassifyExample - .builder() - .text("Nice to know you ;)") - .label("Spam") - .build(), - ClassifyExample - .builder() - .text("Please help me?") - .label("Spam") - .build(), - ClassifyExample - .builder() - .text("Your parcel will be delivered today") - .label("Not spam") - .build(), - ClassifyExample - .builder() - .text("Review changes to our Terms and Conditions") - .label("Not spam") - .build(), - ClassifyExample - .builder() - .text("Weekly sync notes") - .label("Not spam") - .build(), - ClassifyExample - .builder() - .text("'Re: Follow up from today's meeting'") - .label("Not spam") - .build(), - ClassifyExample - .builder() - .text("Pre-read for tomorrow") - .label("Not spam") - .build() - ) - ) - ) - .model("YOUR-FINE-TUNED-MODEL-ID") - .build() - ); - } -} -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**inputs:** `List` - -A list of up to 96 texts to be classified. Each one must be a non-empty string. -There is, however, no consistent, universal limit to the length a particular input can be. We perform classification on the first `x` tokens of each input, and `x` varies depending on which underlying model is powering classification. The maximum token length for each model is listed in the "max tokens" column [here](https://docs.cohere.com/docs/models). -Note: by default the `truncate` parameter is set to `END`, so tokens exceeding the limit will be automatically dropped. This behavior can be disabled by setting `truncate` to `NONE`, which will result in validation errors for longer texts. - -
-
- -
-
- -**examples:** `Optional>` - -An array of examples to provide context to the model. Each example is a text string and its associated label/class. Each unique label requires at least 2 examples associated with it; the maximum number of examples is 2500, and each example has a maximum length of 512 tokens. The values should be structured as `{text: "...",label: "..."}`. -Note: [Fine-tuned Models](https://docs.cohere.com/docs/classify-fine-tuning) trained on classification examples don't require the `examples` parameter to be passed in explicitly. - -
-
- -
-
- -**model:** `Optional` — ID of a [Fine-tuned](https://docs.cohere.com/v2/docs/classify-starting-the-training) Classify model - -
-
- -
-
- -**preset:** `Optional` — The ID of a custom playground preset. You can create presets in the [playground](https://dashboard.cohere.com/playground). If you use a preset, all other parameters become optional, and any included parameters will override the preset's parameters. - -
-
- -
-
- -**truncate:** `Optional` - -One of `NONE|START|END` to specify how the API will handle inputs longer than the maximum token length. -Passing `START` will discard the start of the input. `END` will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. -If `NONE` is selected, when the input exceeds the maximum input token length an error will be returned. - -
-
-
-
- - -
-
-
- -
client.summarize(request) -> SummarizeResponse -
-
- -#### 📝 Description - -
-
- -
-
- - -This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - -Generates a summary in English for a given text. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.summarize( - SummarizeRequest - .builder() - .text("Ice cream is a sweetened frozen food typically eaten as a snack or dessert. It may be made from milk or cream and is flavoured with a sweetener, either sugar or an alternative, and a spice, such as cocoa or vanilla, or with fruit such as strawberries or peaches. It can also be made by whisking a flavored cream base and liquid nitrogen together. Food coloring is sometimes added, in addition to stabilizers. The mixture is cooled below the freezing point of water and stirred to incorporate air spaces and to prevent detectable ice crystals from forming. The result is a smooth, semi-solid foam that is solid at very low temperatures (below 2 °C or 35 °F). It becomes more malleable as its temperature increases.\n\nThe meaning of the name \"ice cream\" varies from one country to another. In some countries, such as the United States, \"ice cream\" applies only to a specific variety, and most governments regulate the commercial use of the various terms according to the relative quantities of the main ingredients, notably the amount of cream. Products that do not meet the criteria to be called ice cream are sometimes labelled \"frozen dairy dessert\" instead. In other countries, such as Italy and Argentina, one word is used fo\r all variants. Analogues made from dairy alternatives, such as goat's or sheep's milk, or milk substitutes (e.g., soy, cashew, coconut, almond milk or tofu), are available for those who are lactose intolerant, allergic to dairy protein or vegan.") - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**text:** `String` — The text to generate a summary for. Can be up to 100,000 characters long. Currently the only supported language is English. - -
-
- -
-
- -**length:** `Optional` — One of `short`, `medium`, `long`, or `auto` defaults to `auto`. Indicates the approximate length of the summary. If `auto` is selected, the best option will be picked based on the input text. - -
-
- -
-
- -**format:** `Optional` — One of `paragraph`, `bullets`, or `auto`, defaults to `auto`. Indicates the style in which the summary will be delivered - in a free form paragraph or in bullet points. If `auto` is selected, the best option will be picked based on the input text. - -
-
- -
-
- -**model:** `Optional` — The identifier of the model to generate the summary with. Currently available models are `command` (default), `command-nightly` (experimental), `command-light`, and `command-light-nightly` (experimental). Smaller, "light" models are faster, while larger models will perform better. - -
-
- -
-
- -**extractiveness:** `Optional` — One of `low`, `medium`, `high`, or `auto`, defaults to `auto`. Controls how close to the original text the summary is. `high` extractiveness summaries will lean towards reusing sentences verbatim, while `low` extractiveness summaries will tend to paraphrase more. If `auto` is selected, the best option will be picked based on the input text. - -
-
- -
-
- -**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. - -
-
- -
-
- -**additionalCommand:** `Optional` — A free-form instruction for modifying how the summaries get generated. Should complete the sentence "Generate a summary _". Eg. "focusing on the next steps" or "written by Yoda" - -
-
-
-
- - -
-
-
- -
client.tokenize(request) -> TokenizeResponse -
-
- -#### 📝 Description - -
-
- -
-
- -This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.tokenize( - TokenizeRequest - .builder() - .text("tokenize me! :D") - .model("command") - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**text:** `String` — The string to be tokenized, the minimum text length is 1 character, and the maximum text length is 65536 characters. - -
-
- -
-
- -**model:** `String` — The input will be tokenized by the tokenizer that is used by this model. - -
-
-
-
- - -
-
-
- -
client.detokenize(request) -> DetokenizeResponse -
-
- -#### 📝 Description - -
-
- -
-
- -This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.detokenize( - DetokenizeRequest - .builder() - .tokens( - new ArrayList( - Arrays.asList(10002, 2261, 2012, 8, 2792, 43) - ) - ) - .model("command") - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**tokens:** `List` — The list of tokens to be detokenized. - -
-
- -
-
- -**model:** `String` — An optional parameter to provide the model name. This will ensure that the detokenization is done by the tokenizer used by that model. - -
-
-
-
- - -
-
-
- -
client.checkApiKey() -> CheckApiKeyResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Checks that the api key in the Authorization header is valid and active -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.checkApiKey(); -``` -
-
-
-
- - -
-
-
- -## V2 -
client.v2.chatStream(request) -> Optional<V2ChatStreamResponse> -
-
- -#### 📝 Description - -
-
- -
-
- -Generates a text response to a user message. To learn how to use the Chat API and RAG follow our [Text Generation guides](https://docs.cohere.com/v2/docs/chat-api). - -Follow the [Migration Guide](https://docs.cohere.com/v2/docs/migrating-v1-to-v2) for instructions on moving from API v1 to API v2. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.v2().chatStream( - V2ChatStreamRequest - .builder() - .model("command-r") - .messages( - new ArrayList( - Arrays.asList( - ChatMessageV2.user( - UserMessageV2 - .builder() - .content( - UserMessageV2Content.of("Hello!") - ) - .build() - ) - ) - ) - ) - .stream(true) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**stream:** `Boolean` - -Defaults to `false`. - -When `true`, the response will be a SSE stream of events. - -Streaming is beneficial for user interfaces that render the contents of the response piece by piece, as it gets generated. - -
-
- -
-
- -**model:** `String` — The name of a compatible [Cohere model](https://docs.cohere.com/v2/docs/models) or the ID of a [fine-tuned](https://docs.cohere.com/v2/docs/chat-fine-tuning) model. - -
-
- -
-
- -**messages:** `List` - -
-
- -
-
- -**tools:** `Optional>` - -A list of tools (functions) available to the model. The model response may contain 'tool_calls' to the specified tools. - -Learn more in the [Tool Use guide](https://docs.cohere.com/docs/tools). - -
-
- -
-
- -**strictTools:** `Optional` - -When set to `true`, tool calls in the Assistant message will be forced to follow the tool definition strictly. Learn more in the [Structured Outputs (Tools) guide](https://docs.cohere.com/docs/structured-outputs-json#structured-outputs-tools). - -**Note**: The first few requests with a new set of tools will take longer to process. - -
-
- -
-
- -**documents:** `Optional>` — A list of relevant documents that the model can cite to generate a more accurate reply. Each document is either a string or document object with content and metadata. - -
-
- -
-
- -**citationOptions:** `Optional` - -
-
- -
-
- -**responseFormat:** `Optional` - -
-
- -
-
- -**safetyMode:** `Optional` - -Used to select the [safety instruction](https://docs.cohere.com/v2/docs/safety-modes) inserted into the prompt. Defaults to `CONTEXTUAL`. -When `OFF` is specified, the safety instruction will be omitted. - -Safety modes are not yet configurable in combination with `tools` and `documents` parameters. - -**Note**: This parameter is only compatible newer Cohere models, starting with [Command R 08-2024](https://docs.cohere.com/docs/command-r#august-2024-release) and [Command R+ 08-2024](https://docs.cohere.com/docs/command-r-plus#august-2024-release). - -**Note**: `command-r7b-12-2024` and newer models only support `"CONTEXTUAL"` and `"STRICT"` modes. - -
-
- -
-
- -**maxTokens:** `Optional` - -The maximum number of tokens the model will generate as part of the response. - -**Note**: Setting a low value may result in incomplete generations. - -
-
- -
-
- -**stopSequences:** `Optional>` — A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence. - -
-
- -
-
- -**temperature:** `Optional` - -Defaults to `0.3`. - -A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations. - -Randomness can be further maximized by increasing the value of the `p` parameter. - -
-
- -
-
- -**seed:** `Optional` - -If specified, the backend will make a best effort to sample tokens -deterministically, such that repeated requests with the same -seed and parameters should return the same result. However, -determinism cannot be totally guaranteed. - -
-
- -
-
- -**frequencyPenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. -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. - -
-
- -
-
- -**presencePenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. -Used to reduce repetitiveness of generated tokens. Similar to `frequency_penalty`, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies. - -
-
- -
-
- -**k:** `Optional` - -Ensures that only the top `k` most likely tokens are considered for generation at each step. When `k` is set to `0`, k-sampling is disabled. -Defaults to `0`, min value of `0`, max value of `500`. - -
-
- -
-
- -**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`. - -
-
- -
-
- -**logprobs:** `Optional` — Defaults to `false`. When set to `true`, the log probabilities of the generated tokens will be included in the response. - -
-
- -
-
- -**toolChoice:** `Optional` - -Used to control whether or not the model will be forced to use a tool when answering. When `REQUIRED` is specified, the model will be forced to use at least one of the user-defined tools, and the `tools` parameter must be passed in the request. -When `NONE` is specified, the model will be forced **not** to use one of the specified tools, and give a direct response. -If tool_choice isn't specified, then the model is free to choose whether to use the specified tools or not. - -**Note**: This parameter is only compatible with models [Command-r7b](https://docs.cohere.com/v2/docs/command-r7b) and newer. - -**Note**: The same functionality can be achieved in `/v1/chat` using the `force_single_step` parameter. If `force_single_step=true`, this is equivalent to specifying `REQUIRED`. While if `force_single_step=true` and `tool_results` are passed, this is equivalent to specifying `NONE`. - -
-
-
-
- - -
-
-
- -
client.v2.chat(request) -> V2ChatResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Generates a text response to a user message and streams it down, token by token. To learn how to use the Chat API with streaming follow our [Text Generation guides](https://docs.cohere.com/v2/docs/chat-api). - -Follow the [Migration Guide](https://docs.cohere.com/v2/docs/migrating-v1-to-v2) for instructions on moving from API v1 to API v2. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.v2().chatStream( - V2ChatStreamRequest - .builder() - .model("command-a-03-2025") - .messages( - new ArrayList( - Arrays.asList( - ChatMessageV2.user( - UserMessageV2 - .builder() - .content( - UserMessageV2Content.of("Tell me about LLMs") - ) - .build() - ) - ) - ) - ) - .stream(false) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**stream:** `Boolean` - -Defaults to `false`. - -When `true`, the response will be a SSE stream of events. - -Streaming is beneficial for user interfaces that render the contents of the response piece by piece, as it gets generated. - -
-
- -
-
- -**model:** `String` — The name of a compatible [Cohere model](https://docs.cohere.com/v2/docs/models) or the ID of a [fine-tuned](https://docs.cohere.com/v2/docs/chat-fine-tuning) model. - -
-
- -
-
- -**messages:** `List` - -
-
- -
-
- -**tools:** `Optional>` - -A list of tools (functions) available to the model. The model response may contain 'tool_calls' to the specified tools. - -Learn more in the [Tool Use guide](https://docs.cohere.com/docs/tools). - -
-
- -
-
- -**strictTools:** `Optional` - -When set to `true`, tool calls in the Assistant message will be forced to follow the tool definition strictly. Learn more in the [Structured Outputs (Tools) guide](https://docs.cohere.com/docs/structured-outputs-json#structured-outputs-tools). - -**Note**: The first few requests with a new set of tools will take longer to process. - -
-
- -
-
- -**documents:** `Optional>` — A list of relevant documents that the model can cite to generate a more accurate reply. Each document is either a string or document object with content and metadata. - -
-
- -
-
- -**citationOptions:** `Optional` - -
-
- -
-
- -**responseFormat:** `Optional` - -
-
- -
-
- -**safetyMode:** `Optional` - -Used to select the [safety instruction](https://docs.cohere.com/v2/docs/safety-modes) inserted into the prompt. Defaults to `CONTEXTUAL`. -When `OFF` is specified, the safety instruction will be omitted. - -Safety modes are not yet configurable in combination with `tools` and `documents` parameters. - -**Note**: This parameter is only compatible newer Cohere models, starting with [Command R 08-2024](https://docs.cohere.com/docs/command-r#august-2024-release) and [Command R+ 08-2024](https://docs.cohere.com/docs/command-r-plus#august-2024-release). - -**Note**: `command-r7b-12-2024` and newer models only support `"CONTEXTUAL"` and `"STRICT"` modes. - -
-
- -
-
- -**maxTokens:** `Optional` - -The maximum number of tokens the model will generate as part of the response. - -**Note**: Setting a low value may result in incomplete generations. - -
-
- -
-
- -**stopSequences:** `Optional>` — A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence. - -
-
- -
-
- -**temperature:** `Optional` - -Defaults to `0.3`. - -A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations. - -Randomness can be further maximized by increasing the value of the `p` parameter. - -
-
- -
-
- -**seed:** `Optional` - -If specified, the backend will make a best effort to sample tokens -deterministically, such that repeated requests with the same -seed and parameters should return the same result. However, -determinism cannot be totally guaranteed. - -
-
- -
-
- -**frequencyPenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. -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. - -
-
- -
-
- -**presencePenalty:** `Optional` - -Defaults to `0.0`, min value of `0.0`, max value of `1.0`. -Used to reduce repetitiveness of generated tokens. Similar to `frequency_penalty`, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies. - -
-
- -
-
- -**k:** `Optional` - -Ensures that only the top `k` most likely tokens are considered for generation at each step. When `k` is set to `0`, k-sampling is disabled. -Defaults to `0`, min value of `0`, max value of `500`. - -
-
- -
-
- -**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`. - -
-
- -
-
- -**logprobs:** `Optional` — Defaults to `false`. When set to `true`, the log probabilities of the generated tokens will be included in the response. - -
-
- -
-
- -**toolChoice:** `Optional` - -Used to control whether or not the model will be forced to use a tool when answering. When `REQUIRED` is specified, the model will be forced to use at least one of the user-defined tools, and the `tools` parameter must be passed in the request. -When `NONE` is specified, the model will be forced **not** to use one of the specified tools, and give a direct response. -If tool_choice isn't specified, then the model is free to choose whether to use the specified tools or not. - -**Note**: This parameter is only compatible with models [Command-r7b](https://docs.cohere.com/v2/docs/command-r7b) and newer. - -**Note**: The same functionality can be achieved in `/v1/chat` using the `force_single_step` parameter. If `force_single_step=true`, this is equivalent to specifying `REQUIRED`. While if `force_single_step=true` and `tool_results` are passed, this is equivalent to specifying `NONE`. - -
-
-
-
- - -
-
-
- -
client.v2.embed(request) -> EmbedByTypeResponse -
-
- -#### 📝 Description - -
-
- -
-
- -This endpoint returns text embeddings. An embedding is a list of floating point numbers that captures semantic information about the text that it represents. - -Embeddings can be used to create text classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page. - -If you want to learn more how to use the embedding model, have a look at the [Semantic Search Guide](https://docs.cohere.com/docs/semantic-search). -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.v2().embed( - V2EmbedRequest - .builder() - .model("embed-v4.0") - .inputType(EmbedInputType.CLASSIFICATION) - .texts( - new ArrayList( - Arrays.asList("hello", "goodbye") - ) - ) - .embeddingTypes( - new ArrayList( - Arrays.asList(EmbeddingType.FLOAT) - ) - ) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**texts:** `Optional>` — An array of strings for the model to embed. Maximum number of texts per call is `96`. - -
-
- -
-
- -**images:** `Optional>` - -An array of image data URIs for the model to embed. Maximum number of images per call is `1`. - -The image must be a valid [data URI](https://developer.mozilla.org/en-US/docs/Web/URI/Schemes/data). The image must be in either `image/jpeg` or `image/png` format and has a maximum size of 5MB. - -Image embeddings are supported with Embed v3.0 and newer models. - -
-
- -
-
- -**model:** `String` — ID of one of the available [Embedding models](https://docs.cohere.com/docs/cohere-embed). - -
-
- -
-
- -**inputType:** `EmbedInputType` - -
-
- -
-
- -**inputs:** `Optional>` — An array of inputs for the model to embed. Maximum number of inputs per call is `96`. An input can contain a mix of text and image components. - -
-
- -
-
- -**maxTokens:** `Optional` — The maximum number of tokens to embed per input. If the input text is longer than this, it will be truncated according to the `truncate` parameter. - -
-
- -
-
- -**outputDimension:** `Optional` - -The number of dimensions of the output embedding. This is only available for `embed-v4` and newer models. -Possible values are `256`, `512`, `1024`, and `1536`. The default is `1536`. - -
-
- -
-
- -**embeddingTypes:** `Optional>` - -Specifies the types of embeddings you want to get back. Can be one or more of the following types. - -* `"float"`: Use this when you want to get back the default float embeddings. Supported with all Embed models. -* `"int8"`: Use this when you want to get back signed int8 embeddings. Supported with Embed v3.0 and newer Embed models. -* `"uint8"`: Use this when you want to get back unsigned int8 embeddings. Supported with Embed v3.0 and newer Embed models. -* `"binary"`: Use this when you want to get back signed binary embeddings. Supported with Embed v3.0 and newer Embed models. -* `"ubinary"`: Use this when you want to get back unsigned binary embeddings. Supported with Embed v3.0 and newer Embed models. - -
-
- -
-
- -**truncate:** `Optional` - -One of `NONE|START|END` to specify how the API will handle inputs longer than the maximum token length. - -Passing `START` will discard the start of the input. `END` will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. - -If `NONE` is selected, when the input exceeds the maximum input token length an error will be returned. - -
-
-
-
- - -
-
-
- -
client.v2.rerank(request) -> V2RerankResponse -
-
- -#### 📝 Description - -
-
- -
-
- -This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -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.") - ) - ) - .query("What is the capital of the United States?") - .model("rerank-v3.5") - .topN(3) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**model:** `String` — The identifier of the model to use, eg `rerank-v3.5`. - -
-
- -
-
- -**query:** `String` — The search query - -
-
- -
-
- -**documents:** `List` - -A list of texts that will be compared to the `query`. -For optimal performance we recommend against sending more than 1,000 documents in a single request. - -**Note**: long documents will automatically be truncated to the value of `max_tokens_per_doc`. - -**Note**: structured data should be formatted as YAML strings for best performance. - -
-
- -
-
- -**topN:** `Optional` — Limits the number of returned rerank results to the specified value. If not passed, all the rerank results will be returned. - -
-
- -
-
- -**maxTokensPerDoc:** `Optional` — Defaults to `4096`. Long documents will be automatically truncated to the specified number of tokens. - -
-
-
-
- - -
-
-
- -## EmbedJobs -
client.embedJobs.list() -> ListEmbedJobResponse -
-
- -#### 📝 Description - -
-
- -
-
- -The list embed job endpoint allows users to view all embed jobs history for that specific user. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.embedJobs().list(); -``` -
-
-
-
- - -
-
-
- -
client.embedJobs.create(request) -> CreateEmbedJobResponse -
-
- -#### 📝 Description - -
-
- -
-
- -This API launches an async Embed job for a [Dataset](https://docs.cohere.com/docs/datasets) of type `embed-input`. The result of a completed embed job is new Dataset of type `embed-output`, which contains the original text entries and the corresponding embeddings. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.embedJobs().create( - CreateEmbedJobRequest - .builder() - .model("model") - .datasetId("dataset_id") - .inputType(EmbedInputType.SEARCH_DOCUMENT) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**model:** `String` - -ID of the embedding model. - -Available models and corresponding embedding dimensions: - -- `embed-english-v3.0` : 1024 -- `embed-multilingual-v3.0` : 1024 -- `embed-english-light-v3.0` : 384 -- `embed-multilingual-light-v3.0` : 384 - -
-
- -
-
- -**datasetId:** `String` — ID of a [Dataset](https://docs.cohere.com/docs/datasets). The Dataset must be of type `embed-input` and must have a validation status `Validated` - -
-
- -
-
- -**inputType:** `EmbedInputType` - -
-
- -
-
- -**name:** `Optional` — The name of the embed job. - -
-
- -
-
- -**embeddingTypes:** `Optional>` - -Specifies the types of embeddings you want to get back. Not required and default is None, which returns the Embed Floats response type. Can be one or more of the following types. - -* `"float"`: Use this when you want to get back the default float embeddings. Valid for all models. -* `"int8"`: Use this when you want to get back signed int8 embeddings. Valid for v3 and newer model versions. -* `"uint8"`: Use this when you want to get back unsigned int8 embeddings. Valid for v3 and newer model versions. -* `"binary"`: Use this when you want to get back signed binary embeddings. Valid for v3 and newer model versions. -* `"ubinary"`: Use this when you want to get back unsigned binary embeddings. Valid for v3 and newer model versions. - -
-
- -
-
- -**truncate:** `Optional` - -One of `START|END` to specify how the API will handle inputs longer than the maximum token length. - -Passing `START` will discard the start of the input. `END` will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. - -
-
-
-
- - -
-
-
- -
client.embedJobs.get(id) -> EmbedJob -
-
- -#### 📝 Description - -
-
- -
-
- -This API retrieves the details about an embed job started by the same user. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.embedJobs().get("id"); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` — The ID of the embed job to retrieve. - -
-
-
-
- - -
-
-
- -
client.embedJobs.cancel(id) -
-
- -#### 📝 Description - -
-
- -
-
- -This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.embedJobs().cancel("id"); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` — The ID of the embed job to cancel. - -
-
-
-
- - -
-
-
- -## Datasets -
client.datasets.list() -> DatasetsListResponse -
-
- -#### 📝 Description - -
-
- -
-
- -List datasets that have been created. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.datasets().list( - DatasetsListRequest - .builder() - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**datasetType:** `Optional` — optional filter by dataset type - -
-
- -
-
- -**before:** `Optional` — optional filter before a date - -
-
- -
-
- -**after:** `Optional` — optional filter after a date - -
-
- -
-
- -**limit:** `Optional` — optional limit to number of results - -
-
- -
-
- -**offset:** `Optional` — optional offset to start of results - -
-
- -
-
- -**validationStatus:** `Optional` — optional filter by validation status - -
-
-
-
- - -
-
-
- -
client.datasets.create(request) -> DatasetsCreateResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Create a dataset by uploading a file. See ['Dataset Creation'](https://docs.cohere.com/docs/datasets#dataset-creation) for more information. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.datasets().create( - DatasetsCreateRequest - .builder() - .name("name") - .type(DatasetType.EMBED_INPUT) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**name:** `String` — The name of the uploaded dataset. - -
-
- -
-
- -**type:** `DatasetType` — The dataset type, which is used to validate the data. Valid types are `embed-input`, `reranker-finetune-input`, `single-label-classification-finetune-input`, `chat-finetune-input`, and `multi-label-classification-finetune-input`. - -
-
- -
-
- -**keepOriginalFile:** `Optional` — Indicates if the original file should be stored. - -
-
- -
-
- -**skipMalformedInput:** `Optional` — Indicates whether rows with malformed input should be dropped (instead of failing the validation check). Dropped rows will be returned in the warnings field. - -
-
- -
-
- -**keepFields:** `Optional` — List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the [schema for the corresponding Dataset type](https://docs.cohere.com/docs/datasets#dataset-types). For example, datasets of type `embed-input` will drop all fields other than the required `text` field. If any of the fields in `keep_fields` are missing from the uploaded file, Dataset validation will fail. - -
-
- -
-
- -**optionalFields:** `Optional` — List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the [schema for the corresponding Dataset type](https://docs.cohere.com/docs/datasets#dataset-types). For example, Datasets of type `embed-input` will drop all fields other than the required `text` field. If any of the fields in `optional_fields` are missing from the uploaded file, Dataset validation will pass. - -
-
- -
-
- -**textSeparator:** `Optional` — Raw .txt uploads will be split into entries using the text_separator value. - -
-
- -
-
- -**csvDelimiter:** `Optional` — The delimiter used for .csv uploads. - -
-
-
-
- - -
-
-
- -
client.datasets.getUsage() -> DatasetsGetUsageResponse -
-
- -#### 📝 Description - -
-
- -
-
- -View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.datasets().getUsage(); -``` -
-
-
-
- - -
-
-
- -
client.datasets.get(id) -> DatasetsGetResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Retrieve a dataset by ID. See ['Datasets'](https://docs.cohere.com/docs/datasets) for more information. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.datasets().get("id"); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` - -
-
-
-
- - -
-
-
- -
client.datasets.delete(id) -> Map<String, Object> -
-
- -#### 📝 Description - -
-
- -
-
- -Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.datasets().delete("id"); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` - -
-
-
-
- - -
-
-
- -## Connectors -
client.connectors.list() -> ListConnectorsResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Returns a list of connectors ordered by descending creation date (newer first). See ['Managing your Connector'](https://docs.cohere.com/docs/managing-your-connector) for more information. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.connectors().list( - ConnectorsListRequest - .builder() - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**limit:** `Optional` — Maximum number of connectors to return [0, 100]. - -
-
- -
-
- -**offset:** `Optional` — Number of connectors to skip before returning results [0, inf]. - -
-
-
-
- - -
-
-
- -
client.connectors.create(request) -> CreateConnectorResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See ['Creating and Deploying a Connector'](https://docs.cohere.com/v1/docs/creating-and-deploying-a-connector) for more information. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.connectors().create( - CreateConnectorRequest - .builder() - .name("name") - .url("url") - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**name:** `String` — A human-readable name for the connector. - -
-
- -
-
- -**description:** `Optional` — A description of the connector. - -
-
- -
-
- -**url:** `String` — The URL of the connector that will be used to search for documents. - -
-
- -
-
- -**excludes:** `Optional>` — A list of fields to exclude from the prompt (fields remain in the document). - -
-
- -
-
- -**oauth:** `Optional` — The OAuth 2.0 configuration for the connector. Cannot be specified if service_auth is specified. - -
-
- -
-
- -**active:** `Optional` — Whether the connector is active or not. - -
-
- -
-
- -**continueOnFailure:** `Optional` — Whether a chat request should continue or not if the request to this connector fails. - -
-
- -
-
- -**serviceAuth:** `Optional` — The service to service authentication configuration for the connector. Cannot be specified if oauth is specified. - -
-
-
-
- - -
-
-
- -
client.connectors.get(id) -> GetConnectorResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Retrieve a connector by ID. See ['Connectors'](https://docs.cohere.com/docs/connectors) for more information. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.connectors().get("id"); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` — The ID of the connector to retrieve. - -
-
-
-
- - -
-
-
- -
client.connectors.delete(id) -> Map<String, Object> -
-
- -#### 📝 Description - -
-
- -
-
- -Delete a connector by ID. See ['Connectors'](https://docs.cohere.com/docs/connectors) for more information. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.connectors().delete("id"); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` — The ID of the connector to delete. - -
-
-
-
- - -
-
-
- -
client.connectors.update(id, request) -> UpdateConnectorResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Update a connector by ID. Omitted fields will not be updated. See ['Managing your Connector'](https://docs.cohere.com/docs/managing-your-connector) for more information. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.connectors().update( - "id", - UpdateConnectorRequest - .builder() - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` — The ID of the connector to update. - -
-
- -
-
- -**name:** `Optional` — A human-readable name for the connector. - -
-
- -
-
- -**url:** `Optional` — The URL of the connector that will be used to search for documents. - -
-
- -
-
- -**excludes:** `Optional>` — A list of fields to exclude from the prompt (fields remain in the document). - -
-
- -
-
- -**oauth:** `Optional` — The OAuth 2.0 configuration for the connector. Cannot be specified if service_auth is specified. - -
-
- -
-
- -**active:** `Optional` - -
-
- -
-
- -**continueOnFailure:** `Optional` - -
-
- -
-
- -**serviceAuth:** `Optional` — The service to service authentication configuration for the connector. Cannot be specified if oauth is specified. - -
-
-
-
- - -
-
-
- -
client.connectors.oAuthAuthorize(id) -> OAuthAuthorizeResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Authorize the connector with the given ID for the connector oauth app. See ['Connector Authentication'](https://docs.cohere.com/docs/connector-authentication) for more information. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.connectors().oAuthAuthorize( - "id", - ConnectorsOAuthAuthorizeRequest - .builder() - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` — The ID of the connector to authorize. - -
-
- -
-
- -**afterTokenRedirect:** `Optional` — The URL to redirect to after the connector has been authorized. - -
-
-
-
- - -
-
-
- -## Models -
client.models.get(model) -> GetModelResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Returns the details of a model, provided its name. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.models().get("command-a-03-2025"); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**model:** `String` - -
-
-
-
- - -
-
-
- -
client.models.list() -> ListModelsResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.models().list( - ModelsListRequest - .builder() - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**pageSize:** `Optional` - -Maximum number of models to include in a page -Defaults to `20`, min value of `1`, max value of `1000`. - -
-
- -
-
- -**pageToken:** `Optional` — Page token provided in the `next_page_token` field of a previous response. - -
-
- -
-
- -**endpoint:** `Optional` — When provided, filters the list of models to only those that are compatible with the specified endpoint. - -
-
- -
-
- -**defaultOnly:** `Optional` — When provided, filters the list of models to only the default model to the endpoint. This parameter is only valid when `endpoint` is provided. - -
-
-
-
- - -
-
-
- -## /finetuning -
client.finetuning.listFinetunedModels() -> ListFinetunedModelsResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Returns a list of fine-tuned models that the user has access to. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.finetuning().listFinetunedModels( - FinetuningListFinetunedModelsRequest - .builder() - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**pageSize:** `Optional` - -Maximum number of results to be returned by the server. If 0, defaults to -50. - -
-
- -
-
- -**pageToken:** `Optional` — Request a specific page of the list results. - -
-
- -
-
- -**orderBy:** `Optional` - -Comma separated list of fields. For example: "created_at,name". The default -sorting order is ascending. To specify descending order for a field, append -" desc" to the field name. For example: "created_at desc,name". - -Supported sorting fields: - - created_at (default) - -
-
-
-
- - -
-
-
- -
client.finetuning.createFinetunedModel(request) -> CreateFinetunedModelResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Creates a new fine-tuned model. The model will be trained on the dataset specified in the request body. The training process may take some time, and the model will be available once the training is complete. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.finetuning().createFinetunedModel( - FinetunedModel - .builder() - .name("api-test") - .settings( - Settings - .builder() - .baseModel( - BaseModel - .builder() - .baseType(BaseType.BASE_TYPE_CHAT) - .build() - ) - .datasetId("my-dataset-id") - .build() - ) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**request:** `FinetunedModel` - -
-
-
-
- - -
-
-
- -
client.finetuning.getFinetunedModel(id) -> GetFinetunedModelResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Retrieve a fine-tuned model by its ID. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.finetuning().getFinetunedModel("id"); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` — The fine-tuned model ID. - -
-
-
-
- - -
-
-
- -
client.finetuning.deleteFinetunedModel(id) -> Map<String, Object> -
-
- -#### 📝 Description - -
-
- -
-
- -Deletes a fine-tuned model. The model will be removed from the system and will no longer be available for use. -This operation is irreversible. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.finetuning().deleteFinetunedModel("id"); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` — The fine-tuned model ID. - -
-
-
-
- - -
-
-
- -
client.finetuning.updateFinetunedModel(id, request) -> UpdateFinetunedModelResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Updates the fine-tuned model with the given ID. The model will be updated with the new settings and name provided in the request body. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.finetuning().updateFinetunedModel( - "id", - FinetuningUpdateFinetunedModelRequest - .builder() - .name("name") - .settings( - Settings - .builder() - .baseModel( - BaseModel - .builder() - .baseType(BaseType.BASE_TYPE_UNSPECIFIED) - .build() - ) - .datasetId("dataset_id") - .build() - ) - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**id:** `String` — FinetunedModel ID. - -
-
- -
-
- -**name:** `String` — FinetunedModel name (e.g. `foobar`). - -
-
- -
-
- -**settings:** `Settings` — FinetunedModel settings such as dataset, hyperparameters... - -
-
- -
-
- -**status:** `Optional` — Current stage in the life-cycle of the fine-tuned model. - -
-
-
-
- - -
-
-
- -
client.finetuning.listEvents(finetunedModelId) -> ListEventsResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Returns a list of events that occurred during the life-cycle of the fine-tuned model. -The events are ordered by creation time, with the most recent event first. -The list can be paginated using `page_size` and `page_token` parameters. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.finetuning().listEvents( - "finetuned_model_id", - FinetuningListEventsRequest - .builder() - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**finetunedModelId:** `String` — The parent fine-tuned model ID. - -
-
- -
-
- -**pageSize:** `Optional` - -Maximum number of results to be returned by the server. If 0, defaults to -50. - -
-
- -
-
- -**pageToken:** `Optional` — Request a specific page of the list results. - -
-
- -
-
- -**orderBy:** `Optional` - -Comma separated list of fields. For example: "created_at,name". The default -sorting order is ascending. To specify descending order for a field, append -" desc" to the field name. For example: "created_at desc,name". - -Supported sorting fields: - - created_at (default) - -
-
-
-
- - -
-
-
- -
client.finetuning.listTrainingStepMetrics(finetunedModelId) -> ListTrainingStepMetricsResponse -
-
- -#### 📝 Description - -
-
- -
-
- -Returns a list of metrics measured during the training of a fine-tuned model. -The metrics are ordered by step number, with the most recent step first. -The list can be paginated using `page_size` and `page_token` parameters. -
-
-
-
- -#### 🔌 Usage - -
-
- -
-
- -```java -client.finetuning().listTrainingStepMetrics( - "finetuned_model_id", - FinetuningListTrainingStepMetricsRequest - .builder() - .build() -); -``` -
-
-
-
- -#### ⚙️ Parameters - -
-
- -
-
- -**finetunedModelId:** `String` — The parent fine-tuned model ID. - -
-
- -
-
- -**pageSize:** `Optional` - -Maximum number of results to be returned by the server. If 0, defaults to -50. - -
-
- -
-
- -**pageToken:** `Optional` — Request a specific page of the list results. - -
-
-
-
- - -
-
-
diff --git a/sample-app/src/main/java/sample/App.java b/sample-app/src/main/java/sample/App.java index 265a292..038ddb0 100644 --- a/sample-app/src/main/java/sample/App.java +++ b/sample-app/src/main/java/sample/App.java @@ -8,6 +8,6 @@ public final class App { public static void main(String[] args) { - // import com.cohere.api.AsyncCohere + // import com.cohere.api.Cohere } } diff --git a/src/main/java/com/cohere/api/AsyncCohere.java b/src/main/java/com/cohere/api/AsyncCohere.java deleted file mode 100644 index 5623a66..0000000 --- a/src/main/java/com/cohere/api/AsyncCohere.java +++ /dev/null @@ -1,294 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.core.Suppliers; -import com.cohere.api.requests.ChatRequest; -import com.cohere.api.requests.ChatStreamRequest; -import com.cohere.api.requests.ClassifyRequest; -import com.cohere.api.requests.DetokenizeRequest; -import com.cohere.api.requests.EmbedRequest; -import com.cohere.api.requests.GenerateRequest; -import com.cohere.api.requests.GenerateStreamRequest; -import com.cohere.api.requests.RerankRequest; -import com.cohere.api.requests.SummarizeRequest; -import com.cohere.api.requests.TokenizeRequest; -import com.cohere.api.resources.connectors.AsyncConnectorsClient; -import com.cohere.api.resources.datasets.AsyncDatasetsClient; -import com.cohere.api.resources.embedjobs.AsyncEmbedJobsClient; -import com.cohere.api.resources.finetuning.AsyncFinetuningClient; -import com.cohere.api.resources.models.AsyncModelsClient; -import com.cohere.api.resources.v2.AsyncV2Client; -import com.cohere.api.types.CheckApiKeyResponse; -import com.cohere.api.types.ClassifyResponse; -import com.cohere.api.types.DetokenizeResponse; -import com.cohere.api.types.EmbedResponse; -import com.cohere.api.types.GenerateStreamedResponse; -import com.cohere.api.types.Generation; -import com.cohere.api.types.NonStreamedChatResponse; -import com.cohere.api.types.RerankResponse; -import com.cohere.api.types.StreamedChatResponse; -import com.cohere.api.types.SummarizeResponse; -import com.cohere.api.types.TokenizeResponse; -import java.util.concurrent.CompletableFuture; -import java.util.function.Supplier; - -public class AsyncCohere { - protected final ClientOptions clientOptions; - - private final AsyncRawCohere rawClient; - - protected final Supplier v2Client; - - protected final Supplier embedJobsClient; - - protected final Supplier datasetsClient; - - protected final Supplier connectorsClient; - - protected final Supplier modelsClient; - - protected final Supplier finetuningClient; - - public AsyncCohere(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawCohere(clientOptions); - this.v2Client = Suppliers.memoize(() -> new AsyncV2Client(clientOptions)); - this.embedJobsClient = Suppliers.memoize(() -> new AsyncEmbedJobsClient(clientOptions)); - this.datasetsClient = Suppliers.memoize(() -> new AsyncDatasetsClient(clientOptions)); - this.connectorsClient = Suppliers.memoize(() -> new AsyncConnectorsClient(clientOptions)); - this.modelsClient = Suppliers.memoize(() -> new AsyncModelsClient(clientOptions)); - this.finetuningClient = Suppliers.memoize(() -> new AsyncFinetuningClient(clientOptions)); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawCohere withRawResponse() { - return this.rawClient; - } - - /** - * Generates a streamed text response to a user message. - *

To learn how to use the Chat API and RAG follow our Text Generation guides.

- */ - public CompletableFuture> chatStream(ChatStreamRequest request) { - return this.rawClient.chatStream(request).thenApply(response -> response.body()); - } - - /** - * Generates a streamed text response to a user message. - *

To learn how to use the Chat API and RAG follow our Text Generation guides.

- */ - public CompletableFuture> chatStream( - ChatStreamRequest request, RequestOptions requestOptions) { - return this.rawClient.chatStream(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Generates a text response to a user message. - * To learn how to use the Chat API and RAG follow our Text Generation guides. - */ - public CompletableFuture chat(ChatRequest request) { - return this.rawClient.chat(request).thenApply(response -> response.body()); - } - - /** - * Generates a text response to a user message. - * To learn how to use the Chat API and RAG follow our Text Generation guides. - */ - public CompletableFuture chat(ChatRequest request, RequestOptions requestOptions) { - return this.rawClient.chat(request, requestOptions).thenApply(response -> response.body()); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat with Streaming API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CompletableFuture> generateStream(GenerateStreamRequest request) { - return this.rawClient.generateStream(request).thenApply(response -> response.body()); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat with Streaming API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CompletableFuture> generateStream( - GenerateStreamRequest request, RequestOptions requestOptions) { - return this.rawClient.generateStream(request, requestOptions).thenApply(response -> response.body()); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CompletableFuture generate(GenerateRequest request) { - return this.rawClient.generate(request).thenApply(response -> response.body()); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CompletableFuture generate(GenerateRequest request, RequestOptions requestOptions) { - return this.rawClient.generate(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - *

Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

- *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

- */ - public CompletableFuture embed() { - return this.rawClient.embed().thenApply(response -> response.body()); - } - - /** - * This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - *

Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

- *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

- */ - public CompletableFuture embed(EmbedRequest request) { - return this.rawClient.embed(request).thenApply(response -> response.body()); - } - - /** - * This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - *

Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

- *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

- */ - public CompletableFuture embed(EmbedRequest request, RequestOptions requestOptions) { - return this.rawClient.embed(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CompletableFuture rerank(RerankRequest request) { - return this.rawClient.rerank(request).thenApply(response -> response.body()); - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CompletableFuture rerank(RerankRequest request, RequestOptions requestOptions) { - return this.rawClient.rerank(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * This endpoint makes a prediction about which label fits the specified text inputs best. To make a prediction, Classify uses the provided examples of text + label pairs as a reference. - * Note: Fine-tuned models trained on classification examples don't require the examples parameter to be passed in explicitly. - */ - public CompletableFuture classify(ClassifyRequest request) { - return this.rawClient.classify(request).thenApply(response -> response.body()); - } - - /** - * This endpoint makes a prediction about which label fits the specified text inputs best. To make a prediction, Classify uses the provided examples of text + label pairs as a reference. - * Note: Fine-tuned models trained on classification examples don't require the examples parameter to be passed in explicitly. - */ - public CompletableFuture classify(ClassifyRequest request, RequestOptions requestOptions) { - return this.rawClient.classify(request, requestOptions).thenApply(response -> response.body()); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates a summary in English for a given text.

- */ - public CompletableFuture summarize(SummarizeRequest request) { - return this.rawClient.summarize(request).thenApply(response -> response.body()); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates a summary in English for a given text.

- */ - public CompletableFuture summarize(SummarizeRequest request, RequestOptions requestOptions) { - return this.rawClient.summarize(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CompletableFuture tokenize(TokenizeRequest request) { - return this.rawClient.tokenize(request).thenApply(response -> response.body()); - } - - /** - * This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CompletableFuture tokenize(TokenizeRequest request, RequestOptions requestOptions) { - return this.rawClient.tokenize(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CompletableFuture detokenize(DetokenizeRequest request) { - return this.rawClient.detokenize(request).thenApply(response -> response.body()); - } - - /** - * This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CompletableFuture detokenize(DetokenizeRequest request, RequestOptions requestOptions) { - return this.rawClient.detokenize(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Checks that the api key in the Authorization header is valid and active - */ - public CompletableFuture checkApiKey() { - return this.rawClient.checkApiKey().thenApply(response -> response.body()); - } - - /** - * Checks that the api key in the Authorization header is valid and active - */ - public CompletableFuture checkApiKey(RequestOptions requestOptions) { - return this.rawClient.checkApiKey(requestOptions).thenApply(response -> response.body()); - } - - public AsyncV2Client v2() { - return this.v2Client.get(); - } - - public AsyncEmbedJobsClient embedJobs() { - return this.embedJobsClient.get(); - } - - public AsyncDatasetsClient datasets() { - return this.datasetsClient.get(); - } - - public AsyncConnectorsClient connectors() { - return this.connectorsClient.get(); - } - - public AsyncModelsClient models() { - return this.modelsClient.get(); - } - - public AsyncFinetuningClient finetuning() { - return this.finetuningClient.get(); - } - - public static AsyncCohereBuilder builder() { - return new AsyncCohereBuilder(); - } -} diff --git a/src/main/java/com/cohere/api/AsyncCohereBuilder.java b/src/main/java/com/cohere/api/AsyncCohereBuilder.java deleted file mode 100644 index 8d89214..0000000 --- a/src/main/java/com/cohere/api/AsyncCohereBuilder.java +++ /dev/null @@ -1,218 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.Environment; -import java.util.Optional; -import okhttp3.OkHttpClient; - -public class AsyncCohereBuilder { - private Optional timeout = Optional.empty(); - - private Optional maxRetries = Optional.empty(); - - private String token = System.getenv("CO_API_KEY"); - - private String clientName = null; - - private Environment environment = Environment.PRODUCTION; - - private OkHttpClient httpClient; - - /** - * Sets token. - * Defaults to the CO_API_KEY environment variable. - */ - public AsyncCohereBuilder token(String token) { - this.token = token; - return this; - } - - /** - * Sets clientName - */ - public AsyncCohereBuilder clientName(String clientName) { - this.clientName = clientName; - return this; - } - - public AsyncCohereBuilder environment(Environment environment) { - this.environment = environment; - return this; - } - - public AsyncCohereBuilder url(String url) { - this.environment = Environment.custom(url); - return this; - } - - /** - * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. - */ - public AsyncCohereBuilder timeout(int timeout) { - this.timeout = Optional.of(timeout); - return this; - } - - /** - * Sets the maximum number of retries for the client. Defaults to 2 retries. - */ - public AsyncCohereBuilder maxRetries(int maxRetries) { - this.maxRetries = Optional.of(maxRetries); - return this; - } - - /** - * Sets the underlying OkHttp client - */ - public AsyncCohereBuilder httpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - protected ClientOptions buildClientOptions() { - ClientOptions.Builder builder = ClientOptions.builder(); - setEnvironment(builder); - setAuthentication(builder); - setCustomHeaders(builder); - setHttpClient(builder); - setTimeouts(builder); - setRetries(builder); - setAdditional(builder); - return builder.build(); - } - - /** - * Sets the environment configuration for the client. - * Override this method to modify URLs or add environment-specific logic. - * - * @param builder The ClientOptions.Builder to configure - */ - protected void setEnvironment(ClientOptions.Builder builder) { - builder.environment(this.environment); - } - - /** - * Override this method to customize authentication. - * This method is called during client options construction to set up authentication headers. - * - * @param builder The ClientOptions.Builder to configure - * - * Example: - *
{@code
-     * @Override
-     * protected void setAuthentication(ClientOptions.Builder builder) {
-     *     super.setAuthentication(builder); // Keep existing auth
-     *     builder.addHeader("X-API-Key", this.apiKey);
-     * }
-     * }
- */ - protected void setAuthentication(ClientOptions.Builder builder) { - if (this.token != null) { - builder.addHeader("Authorization", "Bearer " + this.token); - } - } - - /** - * Override this method to add or modify custom headers. - * This method is called during client options construction to set up custom headers defined in the API. - * - * @param builder The ClientOptions.Builder to configure - * - * Example: - *
{@code
-     * @Override
-     * protected void setCustomHeaders(ClientOptions.Builder builder) {
-     *     super.setCustomHeaders(builder); // Keep existing headers
-     *     builder.addHeader("X-Trace-ID", generateTraceId());
-     * }
-     * }
- */ - protected void setCustomHeaders(ClientOptions.Builder builder) { - if (this.clientName != null) { - builder.addHeader("X-Client-Name", this.clientName); - } - } - - /** - * Sets the request timeout configuration. - * Override this method to customize timeout behavior. - * - * @param builder The ClientOptions.Builder to configure - */ - protected void setTimeouts(ClientOptions.Builder builder) { - if (this.timeout.isPresent()) { - builder.timeout(this.timeout.get()); - } - } - - /** - * Sets the retry configuration for failed requests. - * Override this method to implement custom retry strategies. - * - * @param builder The ClientOptions.Builder to configure - */ - protected void setRetries(ClientOptions.Builder builder) { - if (this.maxRetries.isPresent()) { - builder.maxRetries(this.maxRetries.get()); - } - } - - /** - * Sets the OkHttp client configuration. - * Override this method to customize HTTP client behavior (interceptors, connection pools, etc). - * - * @param builder The ClientOptions.Builder to configure - */ - protected void setHttpClient(ClientOptions.Builder builder) { - if (this.httpClient != null) { - builder.httpClient(this.httpClient); - } - } - - /** - * Override this method to add any additional configuration to the client. - * This method is called at the end of the configuration chain, allowing you to add - * custom headers, modify settings, or perform any other client customization. - * - * @param builder The ClientOptions.Builder to configure - * - * Example: - *
{@code
-     * @Override
-     * protected void setAdditional(ClientOptions.Builder builder) {
-     *     builder.addHeader("X-Request-ID", () -> UUID.randomUUID().toString());
-     *     builder.addHeader("X-Client-Version", "1.0.0");
-     * }
-     * }
- */ - protected void setAdditional(ClientOptions.Builder builder) {} - - /** - * Override this method to add custom validation logic before the client is built. - * This method is called at the beginning of the build() method to ensure the configuration is valid. - * Throw an exception to prevent client creation if validation fails. - * - * Example: - *
{@code
-     * @Override
-     * protected void validateConfiguration() {
-     *     super.validateConfiguration(); // Run parent validations
-     *     if (tenantId == null || tenantId.isEmpty()) {
-     *         throw new IllegalStateException("tenantId is required");
-     *     }
-     * }
-     * }
- */ - protected void validateConfiguration() {} - - public AsyncCohere build() { - if (token == null) { - throw new RuntimeException("Please provide token or set the CO_API_KEY environment variable."); - } - validateConfiguration(); - return new AsyncCohere(buildClientOptions()); - } -} diff --git a/src/main/java/com/cohere/api/AsyncRawCohere.java b/src/main/java/com/cohere/api/AsyncRawCohere.java deleted file mode 100644 index c3728c4..0000000 --- a/src/main/java/com/cohere/api/AsyncRawCohere.java +++ /dev/null @@ -1,1694 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.core.ResponseBodyReader; -import com.cohere.api.core.Stream; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.requests.ChatRequest; -import com.cohere.api.requests.ChatStreamRequest; -import com.cohere.api.requests.ClassifyRequest; -import com.cohere.api.requests.DetokenizeRequest; -import com.cohere.api.requests.EmbedRequest; -import com.cohere.api.requests.GenerateRequest; -import com.cohere.api.requests.GenerateStreamRequest; -import com.cohere.api.requests.RerankRequest; -import com.cohere.api.requests.SummarizeRequest; -import com.cohere.api.requests.TokenizeRequest; -import com.cohere.api.types.CheckApiKeyResponse; -import com.cohere.api.types.ClassifyResponse; -import com.cohere.api.types.DetokenizeResponse; -import com.cohere.api.types.EmbedResponse; -import com.cohere.api.types.GenerateStreamedResponse; -import com.cohere.api.types.Generation; -import com.cohere.api.types.NonStreamedChatResponse; -import com.cohere.api.types.RerankResponse; -import com.cohere.api.types.StreamedChatResponse; -import com.cohere.api.types.SummarizeResponse; -import com.cohere.api.types.TokenizeResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; - -public class AsyncRawCohere { - protected final ClientOptions clientOptions; - - public AsyncRawCohere(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Generates a streamed text response to a user message. - *

To learn how to use the Chat API and RAG follow our Text Generation guides.

- */ - public CompletableFuture>> chatStream(ChatStreamRequest request) { - return chatStream(request, null); - } - - /** - * Generates a streamed text response to a user message. - *

To learn how to use the Chat API and RAG follow our Text Generation guides.

- */ - public CompletableFuture>> chatStream( - ChatStreamRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/chat") - .build(); - Map properties = new HashMap<>(); - properties.put("message", request.getMessage()); - if (request.getModel().isPresent()) { - 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.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()); - } - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - if (request.getAccepts().isPresent()) { - _requestBuilder.addHeader("Accepts", request.getAccepts().get()); - } - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture>> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - Stream.fromJson(StreamedChatResponse.class, new ResponseBodyReader(response), "\\n"), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Generates a text response to a user message. - * To learn how to use the Chat API and RAG follow our Text Generation guides. - */ - public CompletableFuture> chat(ChatRequest request) { - return chat(request, null); - } - - /** - * Generates a text response to a user message. - * To learn how to use the Chat API and RAG follow our Text Generation guides. - */ - public CompletableFuture> chat( - ChatRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/chat") - .build(); - Map properties = new HashMap<>(); - properties.put("message", request.getMessage()); - if (request.getModel().isPresent()) { - 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.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()); - } - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - if (request.getAccepts().isPresent()) { - _requestBuilder.addHeader("Accepts", request.getAccepts().get()); - } - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), NonStreamedChatResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat with Streaming API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CompletableFuture>> generateStream( - GenerateStreamRequest request) { - return generateStream(request, null); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat with Streaming API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CompletableFuture>> generateStream( - GenerateStreamRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/generate") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture>> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - Stream.fromJson( - GenerateStreamedResponse.class, new ResponseBodyReader(response), "\\n"), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CompletableFuture> generate(GenerateRequest request) { - return generate(request, null); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CompletableFuture> generate( - GenerateRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/generate") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Generation.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - *

Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

- *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

- */ - public CompletableFuture> embed() { - return embed(EmbedRequest.builder().build()); - } - - /** - * This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - *

Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

- *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

- */ - public CompletableFuture> embed(EmbedRequest request) { - return embed(request, null); - } - - /** - * This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - *

Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

- *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

- */ - public CompletableFuture> embed( - EmbedRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CompletableFuture> rerank(RerankRequest request) { - return rerank(request, null); - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CompletableFuture> rerank( - RerankRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/rerank") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), RerankResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This endpoint makes a prediction about which label fits the specified text inputs best. To make a prediction, Classify uses the provided examples of text + label pairs as a reference. - * Note: Fine-tuned models trained on classification examples don't require the examples parameter to be passed in explicitly. - */ - public CompletableFuture> classify(ClassifyRequest request) { - return classify(request, null); - } - - /** - * This endpoint makes a prediction about which label fits the specified text inputs best. To make a prediction, Classify uses the provided examples of text + label pairs as a reference. - * Note: Fine-tuned models trained on classification examples don't require the examples parameter to be passed in explicitly. - */ - public CompletableFuture> classify( - ClassifyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/classify") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ClassifyResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates a summary in English for a given text.

- */ - public CompletableFuture> summarize(SummarizeRequest request) { - return summarize(request, null); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates a summary in English for a given text.

- */ - public CompletableFuture> summarize( - SummarizeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/summarize") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SummarizeResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CompletableFuture> tokenize(TokenizeRequest request) { - return tokenize(request, null); - } - - /** - * This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CompletableFuture> tokenize( - TokenizeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/tokenize") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TokenizeResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CompletableFuture> detokenize(DetokenizeRequest request) { - return detokenize(request, null); - } - - /** - * This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CompletableFuture> detokenize( - DetokenizeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detokenize") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DetokenizeResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Checks that the api key in the Authorization header is valid and active - */ - public CompletableFuture> checkApiKey() { - return checkApiKey(null); - } - - /** - * Checks that the api key in the Authorization header is valid and active - */ - public CompletableFuture> checkApiKey(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/check-api-key") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CheckApiKeyResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/src/main/java/com/cohere/api/Cohere.java b/src/main/java/com/cohere/api/Cohere.java index aa2a15e..e1eb266 100644 --- a/src/main/java/com/cohere/api/Cohere.java +++ b/src/main/java/com/cohere/api/Cohere.java @@ -4,8 +4,26 @@ package com.cohere.api; import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.CohereApiException; +import com.cohere.api.core.CohereException; +import com.cohere.api.core.MediaTypes; +import com.cohere.api.core.ObjectMappers; import com.cohere.api.core.RequestOptions; +import com.cohere.api.core.ResponseBodyReader; +import com.cohere.api.core.Stream; import com.cohere.api.core.Suppliers; +import com.cohere.api.errors.BadRequestError; +import com.cohere.api.errors.ClientClosedRequestError; +import com.cohere.api.errors.ForbiddenError; +import com.cohere.api.errors.GatewayTimeoutError; +import com.cohere.api.errors.InternalServerError; +import com.cohere.api.errors.InvalidTokenError; +import com.cohere.api.errors.NotFoundError; +import com.cohere.api.errors.NotImplementedError; +import com.cohere.api.errors.ServiceUnavailableError; +import com.cohere.api.errors.TooManyRequestsError; +import com.cohere.api.errors.UnauthorizedError; +import com.cohere.api.errors.UnprocessableEntityError; import com.cohere.api.requests.ChatRequest; import com.cohere.api.requests.ChatStreamRequest; import com.cohere.api.requests.ClassifyRequest; @@ -33,13 +51,22 @@ import com.cohere.api.types.StreamedChatResponse; import com.cohere.api.types.SummarizeResponse; import com.cohere.api.types.TokenizeResponse; +import com.fasterxml.jackson.core.JsonProcessingException; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.function.Supplier; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class Cohere { protected final ClientOptions clientOptions; - private final RawCohere rawClient; - protected final Supplier v2Client; protected final Supplier embedJobsClient; @@ -54,7 +81,6 @@ public class Cohere { public Cohere(ClientOptions clientOptions) { this.clientOptions = clientOptions; - this.rawClient = new RawCohere(clientOptions); this.v2Client = Suppliers.memoize(() -> new V2Client(clientOptions)); this.embedJobsClient = Suppliers.memoize(() -> new EmbedJobsClient(clientOptions)); this.datasetsClient = Suppliers.memoize(() -> new DatasetsClient(clientOptions)); @@ -63,19 +89,12 @@ public Cohere(ClientOptions clientOptions) { this.finetuningClient = Suppliers.memoize(() -> new FinetuningClient(clientOptions)); } - /** - * Get responses with HTTP metadata like headers - */ - public RawCohere withRawResponse() { - return this.rawClient; - } - /** * Generates a streamed text response to a user message. *

To learn how to use the Chat API and RAG follow our Text Generation guides.

*/ public Iterable chatStream(ChatStreamRequest request) { - return this.rawClient.chatStream(request).body(); + return chatStream(request, null); } /** @@ -83,7 +102,163 @@ public Iterable chatStream(ChatStreamRequest request) { *

To learn how to use the Chat API and RAG follow our Text Generation guides.

*/ public Iterable chatStream(ChatStreamRequest request, RequestOptions requestOptions) { - return this.rawClient.chatStream(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/chat") + .build(); + Map properties = new HashMap<>(); + properties.put("message", request.getMessage()); + if (request.getModel().isPresent()) { + 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.getReturnPrompt().isPresent()) { + properties.put("return_prompt", request.getReturnPrompt()); + } + 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()); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); + } catch (Exception e) { + throw new RuntimeException(e); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json"); + if (request.getAccepts().isPresent()) { + _requestBuilder.addHeader("Accepts", request.getAccepts().get()); + } + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try { + Response response = client.newCall(okhttpRequest).execute(); + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new Stream( + StreamedChatResponse.class, new ResponseBodyReader(response), "\n"); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -91,7 +266,7 @@ public Iterable chatStream(ChatStreamRequest request, Requ * To learn how to use the Chat API and RAG follow our Text Generation guides. */ public NonStreamedChatResponse chat(ChatRequest request) { - return this.rawClient.chat(request).body(); + return chat(request, null); } /** @@ -99,7 +274,161 @@ public NonStreamedChatResponse chat(ChatRequest request) { * To learn how to use the Chat API and RAG follow our Text Generation guides. */ public NonStreamedChatResponse chat(ChatRequest request, RequestOptions requestOptions) { - return this.rawClient.chat(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/chat") + .build(); + Map properties = new HashMap<>(); + properties.put("message", request.getMessage()); + if (request.getModel().isPresent()) { + 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.getReturnPrompt().isPresent()) { + properties.put("return_prompt", request.getReturnPrompt()); + } + 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()); + } + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); + } catch (Exception e) { + throw new RuntimeException(e); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json"); + if (request.getAccepts().isPresent()) { + _requestBuilder.addHeader("Accepts", request.getAccepts().get()); + } + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NonStreamedChatResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -109,7 +438,7 @@ public NonStreamedChatResponse chat(ChatRequest request, RequestOptions requestO * Generates realistic text conditioned on a given input.

*/ public Iterable generateStream(GenerateStreamRequest request) { - return this.rawClient.generateStream(request).body(); + return generateStream(request, null); } /** @@ -120,7 +449,82 @@ public Iterable generateStream(GenerateStreamRequest r */ public Iterable generateStream( GenerateStreamRequest request, RequestOptions requestOptions) { - return this.rawClient.generateStream(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/generate") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try { + Response response = client.newCall(okhttpRequest).execute(); + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new Stream( + GenerateStreamedResponse.class, new ResponseBodyReader(response), "\n"); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -130,7 +534,7 @@ public Iterable generateStream( * Generates realistic text conditioned on a given input.

*/ public Generation generate(GenerateRequest request) { - return this.rawClient.generate(request).body(); + return generate(request, null); } /** @@ -140,7 +544,80 @@ public Generation generate(GenerateRequest request) { * Generates realistic text conditioned on a given input.

*/ public Generation generate(GenerateRequest request, RequestOptions requestOptions) { - return this.rawClient.generate(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/generate") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Generation.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -149,7 +626,7 @@ public Generation generate(GenerateRequest request, RequestOptions requestOption *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

*/ public EmbedResponse embed() { - return this.rawClient.embed().body(); + return embed(EmbedRequest.builder().build()); } /** @@ -158,7 +635,7 @@ public EmbedResponse embed() { *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

*/ public EmbedResponse embed(EmbedRequest request) { - return this.rawClient.embed(request).body(); + return embed(request, null); } /** @@ -167,21 +644,167 @@ public EmbedResponse embed(EmbedRequest request) { *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

*/ public EmbedResponse embed(EmbedRequest request, RequestOptions requestOptions) { - return this.rawClient.embed(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/embed") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. */ public RerankResponse rerank(RerankRequest request) { - return this.rawClient.rerank(request).body(); + return rerank(request, null); } /** * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. */ public RerankResponse rerank(RerankRequest request, RequestOptions requestOptions) { - return this.rawClient.rerank(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/rerank") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), RerankResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -189,7 +812,7 @@ public RerankResponse rerank(RerankRequest request, RequestOptions requestOption * Note: Fine-tuned models trained on classification examples don't require the examples parameter to be passed in explicitly. */ public ClassifyResponse classify(ClassifyRequest request) { - return this.rawClient.classify(request).body(); + return classify(request, null); } /** @@ -197,7 +820,80 @@ public ClassifyResponse classify(ClassifyRequest request) { * Note: Fine-tuned models trained on classification examples don't require the examples parameter to be passed in explicitly. */ public ClassifyResponse classify(ClassifyRequest request, RequestOptions requestOptions) { - return this.rawClient.classify(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/classify") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ClassifyResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -207,7 +903,7 @@ public ClassifyResponse classify(ClassifyRequest request, RequestOptions request * Generates a summary in English for a given text.

*/ public SummarizeResponse summarize(SummarizeRequest request) { - return this.rawClient.summarize(request).body(); + return summarize(request, null); } /** @@ -217,49 +913,334 @@ public SummarizeResponse summarize(SummarizeRequest request) { * Generates a summary in English for a given text.

*/ public SummarizeResponse summarize(SummarizeRequest request, RequestOptions requestOptions) { - return this.rawClient.summarize(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/summarize") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SummarizeResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page. */ public TokenizeResponse tokenize(TokenizeRequest request) { - return this.rawClient.tokenize(request).body(); + return tokenize(request, null); } /** * This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page. */ public TokenizeResponse tokenize(TokenizeRequest request, RequestOptions requestOptions) { - return this.rawClient.tokenize(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/tokenize") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TokenizeResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page. */ public DetokenizeResponse detokenize(DetokenizeRequest request) { - return this.rawClient.detokenize(request).body(); + return detokenize(request, null); } /** * This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page. */ public DetokenizeResponse detokenize(DetokenizeRequest request, RequestOptions requestOptions) { - return this.rawClient.detokenize(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detokenize") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DetokenizeResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Checks that the api key in the Authorization header is valid and active */ public CheckApiKeyResponse checkApiKey() { - return this.rawClient.checkApiKey().body(); + return checkApiKey(null); } /** * Checks that the api key in the Authorization header is valid and active */ public CheckApiKeyResponse checkApiKey(RequestOptions requestOptions) { - return this.rawClient.checkApiKey(requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/check-api-key") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CheckApiKeyResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } public V2Client v2() { diff --git a/src/main/java/com/cohere/api/CohereBuilder.java b/src/main/java/com/cohere/api/CohereBuilder.java index 2050387..133039f 100644 --- a/src/main/java/com/cohere/api/CohereBuilder.java +++ b/src/main/java/com/cohere/api/CohereBuilder.java @@ -5,13 +5,9 @@ import com.cohere.api.core.ClientOptions; import com.cohere.api.core.Environment; -import java.util.Optional; -import okhttp3.OkHttpClient; -public class CohereBuilder { - private Optional timeout = Optional.empty(); - - private Optional maxRetries = Optional.empty(); +public final class CohereBuilder { + private ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder(); private String token = System.getenv("CO_API_KEY"); @@ -19,8 +15,6 @@ public class CohereBuilder { private Environment environment = Environment.PRODUCTION; - private OkHttpClient httpClient; - /** * Sets token. * Defaults to the CO_API_KEY environment variable. @@ -48,171 +42,15 @@ public CohereBuilder url(String url) { return this; } - /** - * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. - */ - public CohereBuilder timeout(int timeout) { - this.timeout = Optional.of(timeout); - return this; - } - - /** - * Sets the maximum number of retries for the client. Defaults to 2 retries. - */ - public CohereBuilder maxRetries(int maxRetries) { - this.maxRetries = Optional.of(maxRetries); - return this; - } - - /** - * Sets the underlying OkHttp client - */ - public CohereBuilder httpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - protected ClientOptions buildClientOptions() { - ClientOptions.Builder builder = ClientOptions.builder(); - setEnvironment(builder); - setAuthentication(builder); - setCustomHeaders(builder); - setHttpClient(builder); - setTimeouts(builder); - setRetries(builder); - setAdditional(builder); - return builder.build(); - } - - /** - * Sets the environment configuration for the client. - * Override this method to modify URLs or add environment-specific logic. - * - * @param builder The ClientOptions.Builder to configure - */ - protected void setEnvironment(ClientOptions.Builder builder) { - builder.environment(this.environment); - } - - /** - * Override this method to customize authentication. - * This method is called during client options construction to set up authentication headers. - * - * @param builder The ClientOptions.Builder to configure - * - * Example: - *
{@code
-     * @Override
-     * protected void setAuthentication(ClientOptions.Builder builder) {
-     *     super.setAuthentication(builder); // Keep existing auth
-     *     builder.addHeader("X-API-Key", this.apiKey);
-     * }
-     * }
- */ - protected void setAuthentication(ClientOptions.Builder builder) { - if (this.token != null) { - builder.addHeader("Authorization", "Bearer " + this.token); - } - } - - /** - * Override this method to add or modify custom headers. - * This method is called during client options construction to set up custom headers defined in the API. - * - * @param builder The ClientOptions.Builder to configure - * - * Example: - *
{@code
-     * @Override
-     * protected void setCustomHeaders(ClientOptions.Builder builder) {
-     *     super.setCustomHeaders(builder); // Keep existing headers
-     *     builder.addHeader("X-Trace-ID", generateTraceId());
-     * }
-     * }
- */ - protected void setCustomHeaders(ClientOptions.Builder builder) { - if (this.clientName != null) { - builder.addHeader("X-Client-Name", this.clientName); - } - } - - /** - * Sets the request timeout configuration. - * Override this method to customize timeout behavior. - * - * @param builder The ClientOptions.Builder to configure - */ - protected void setTimeouts(ClientOptions.Builder builder) { - if (this.timeout.isPresent()) { - builder.timeout(this.timeout.get()); - } - } - - /** - * Sets the retry configuration for failed requests. - * Override this method to implement custom retry strategies. - * - * @param builder The ClientOptions.Builder to configure - */ - protected void setRetries(ClientOptions.Builder builder) { - if (this.maxRetries.isPresent()) { - builder.maxRetries(this.maxRetries.get()); - } - } - - /** - * Sets the OkHttp client configuration. - * Override this method to customize HTTP client behavior (interceptors, connection pools, etc). - * - * @param builder The ClientOptions.Builder to configure - */ - protected void setHttpClient(ClientOptions.Builder builder) { - if (this.httpClient != null) { - builder.httpClient(this.httpClient); - } - } - - /** - * Override this method to add any additional configuration to the client. - * This method is called at the end of the configuration chain, allowing you to add - * custom headers, modify settings, or perform any other client customization. - * - * @param builder The ClientOptions.Builder to configure - * - * Example: - *
{@code
-     * @Override
-     * protected void setAdditional(ClientOptions.Builder builder) {
-     *     builder.addHeader("X-Request-ID", () -> UUID.randomUUID().toString());
-     *     builder.addHeader("X-Client-Version", "1.0.0");
-     * }
-     * }
- */ - protected void setAdditional(ClientOptions.Builder builder) {} - - /** - * Override this method to add custom validation logic before the client is built. - * This method is called at the beginning of the build() method to ensure the configuration is valid. - * Throw an exception to prevent client creation if validation fails. - * - * Example: - *
{@code
-     * @Override
-     * protected void validateConfiguration() {
-     *     super.validateConfiguration(); // Run parent validations
-     *     if (tenantId == null || tenantId.isEmpty()) {
-     *         throw new IllegalStateException("tenantId is required");
-     *     }
-     * }
-     * }
- */ - protected void validateConfiguration() {} - public Cohere build() { if (token == null) { throw new RuntimeException("Please provide token or set the CO_API_KEY environment variable."); } - validateConfiguration(); - return new Cohere(buildClientOptions()); + this.clientOptionsBuilder.addHeader("Authorization", "Bearer " + this.token); + if (clientName != null) { + this.clientOptionsBuilder.addHeader("X-Client-Name", this.clientName); + } + clientOptionsBuilder.environment(this.environment); + return new Cohere(clientOptionsBuilder.build()); } } diff --git a/src/main/java/com/cohere/api/RawCohere.java b/src/main/java/com/cohere/api/RawCohere.java deleted file mode 100644 index 3f3ec4e..0000000 --- a/src/main/java/com/cohere/api/RawCohere.java +++ /dev/null @@ -1,1264 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.core.ResponseBodyReader; -import com.cohere.api.core.Stream; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.requests.ChatRequest; -import com.cohere.api.requests.ChatStreamRequest; -import com.cohere.api.requests.ClassifyRequest; -import com.cohere.api.requests.DetokenizeRequest; -import com.cohere.api.requests.EmbedRequest; -import com.cohere.api.requests.GenerateRequest; -import com.cohere.api.requests.GenerateStreamRequest; -import com.cohere.api.requests.RerankRequest; -import com.cohere.api.requests.SummarizeRequest; -import com.cohere.api.requests.TokenizeRequest; -import com.cohere.api.types.CheckApiKeyResponse; -import com.cohere.api.types.ClassifyResponse; -import com.cohere.api.types.DetokenizeResponse; -import com.cohere.api.types.EmbedResponse; -import com.cohere.api.types.GenerateStreamedResponse; -import com.cohere.api.types.Generation; -import com.cohere.api.types.NonStreamedChatResponse; -import com.cohere.api.types.RerankResponse; -import com.cohere.api.types.StreamedChatResponse; -import com.cohere.api.types.SummarizeResponse; -import com.cohere.api.types.TokenizeResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; - -public class RawCohere { - protected final ClientOptions clientOptions; - - public RawCohere(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Generates a streamed text response to a user message. - *

To learn how to use the Chat API and RAG follow our Text Generation guides.

- */ - public CohereHttpResponse> chatStream(ChatStreamRequest request) { - return chatStream(request, null); - } - - /** - * Generates a streamed text response to a user message. - *

To learn how to use the Chat API and RAG follow our Text Generation guides.

- */ - public CohereHttpResponse> chatStream( - ChatStreamRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/chat") - .build(); - Map properties = new HashMap<>(); - properties.put("message", request.getMessage()); - if (request.getModel().isPresent()) { - 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.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()); - } - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - if (request.getAccepts().isPresent()) { - _requestBuilder.addHeader("Accepts", request.getAccepts().get()); - } - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try { - Response response = client.newCall(okhttpRequest).execute(); - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - Stream.fromJson(StreamedChatResponse.class, new ResponseBodyReader(response), "\\n"), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Generates a text response to a user message. - * To learn how to use the Chat API and RAG follow our Text Generation guides. - */ - public CohereHttpResponse chat(ChatRequest request) { - return chat(request, null); - } - - /** - * Generates a text response to a user message. - * To learn how to use the Chat API and RAG follow our Text Generation guides. - */ - public CohereHttpResponse chat(ChatRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/chat") - .build(); - Map properties = new HashMap<>(); - properties.put("message", request.getMessage()); - if (request.getModel().isPresent()) { - 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.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()); - } - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(properties), MediaTypes.APPLICATION_JSON); - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json"); - if (request.getAccepts().isPresent()) { - _requestBuilder.addHeader("Accepts", request.getAccepts().get()); - } - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NonStreamedChatResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat with Streaming API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CohereHttpResponse> generateStream(GenerateStreamRequest request) { - return generateStream(request, null); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat with Streaming API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CohereHttpResponse> generateStream( - GenerateStreamRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/generate") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try { - Response response = client.newCall(okhttpRequest).execute(); - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - Stream.fromJson(GenerateStreamedResponse.class, new ResponseBodyReader(response), "\\n"), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CohereHttpResponse generate(GenerateRequest request) { - return generate(request, null); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates realistic text conditioned on a given input.

- */ - public CohereHttpResponse generate(GenerateRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/generate") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Generation.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - *

Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

- *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

- */ - public CohereHttpResponse embed() { - return embed(EmbedRequest.builder().build()); - } - - /** - * This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - *

Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

- *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

- */ - public CohereHttpResponse embed(EmbedRequest request) { - return embed(request, null); - } - - /** - * This endpoint returns text and image embeddings. An embedding is a list of floating point numbers that captures semantic information about the content that it represents. - *

Embeddings can be used to create classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

- *

If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

- */ - public CohereHttpResponse embed(EmbedRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CohereHttpResponse rerank(RerankRequest request) { - return rerank(request, null); - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CohereHttpResponse rerank(RerankRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/rerank") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), RerankResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This endpoint makes a prediction about which label fits the specified text inputs best. To make a prediction, Classify uses the provided examples of text + label pairs as a reference. - * Note: Fine-tuned models trained on classification examples don't require the examples parameter to be passed in explicitly. - */ - public CohereHttpResponse classify(ClassifyRequest request) { - return classify(request, null); - } - - /** - * This endpoint makes a prediction about which label fits the specified text inputs best. To make a prediction, Classify uses the provided examples of text + label pairs as a reference. - * Note: Fine-tuned models trained on classification examples don't require the examples parameter to be passed in explicitly. - */ - public CohereHttpResponse classify(ClassifyRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/classify") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ClassifyResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates a summary in English for a given text.

- */ - public CohereHttpResponse summarize(SummarizeRequest request) { - return summarize(request, null); - } - - /** - *

<Warning> - * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](https://docs.cohere.com/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API. - * </Warning> - * Generates a summary in English for a given text.

- */ - public CohereHttpResponse summarize(SummarizeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/summarize") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SummarizeResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CohereHttpResponse tokenize(TokenizeRequest request) { - return tokenize(request, null); - } - - /** - * This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CohereHttpResponse tokenize(TokenizeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/tokenize") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TokenizeResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CohereHttpResponse detokenize(DetokenizeRequest request) { - return detokenize(request, null); - } - - /** - * This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page. - */ - public CohereHttpResponse detokenize(DetokenizeRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detokenize") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DetokenizeResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Checks that the api key in the Authorization header is valid and active - */ - public CohereHttpResponse checkApiKey() { - return checkApiKey(null); - } - - /** - * Checks that the api key in the Authorization header is valid and active - */ - public CohereHttpResponse checkApiKey(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/check-api-key") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CheckApiKeyResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - 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..0d1a22f 100644 --- a/src/main/java/com/cohere/api/core/ClientOptions.java +++ b/src/main/java/com/cohere/api/core/ClientOptions.java @@ -5,7 +5,6 @@ import java.util.HashMap; import java.util.Map; -import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import okhttp3.OkHttpClient; @@ -19,28 +18,23 @@ public final class ClientOptions { private final OkHttpClient httpClient; - private final int timeout; - private ClientOptions( Environment environment, Map headers, Map> headerSuppliers, - OkHttpClient httpClient, - int timeout) { + OkHttpClient httpClient) { 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("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", "0.0.1"); } }); this.headerSuppliers = headerSuppliers; this.httpClient = httpClient; - this.timeout = timeout; } public Environment environment() { @@ -58,13 +52,6 @@ public Map headers(RequestOptions requestOptions) { return values; } - public int timeout(RequestOptions requestOptions) { - if (requestOptions == null) { - return this.timeout; - } - return requestOptions.getTimeout().orElse(this.timeout); - } - public OkHttpClient httpClient() { return this.httpClient; } @@ -86,19 +73,13 @@ public static Builder builder() { return new Builder(); } - public static class Builder { + public static final class Builder { private Environment environment; private final Map headers = new HashMap<>(); private final Map> headerSuppliers = new HashMap<>(); - private int maxRetries = 2; - - private Optional timeout = Optional.empty(); - - private OkHttpClient httpClient = null; - public Builder environment(Environment environment) { this.environment = environment; return this; @@ -114,69 +95,11 @@ public Builder addHeader(String key, Supplier value) { return this; } - /** - * Override the timeout in seconds. Defaults to 60 seconds. - */ - public Builder timeout(int timeout) { - this.timeout = Optional.of(timeout); - return this; - } - - /** - * Override the timeout in seconds. Defaults to 60 seconds. - */ - public Builder timeout(Optional timeout) { - this.timeout = timeout; - return this; - } - - /** - * Override the maximum number of retries. Defaults to 2 retries. - */ - public Builder maxRetries(int maxRetries) { - this.maxRetries = maxRetries; - return this; - } - - public Builder httpClient(OkHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - public ClientOptions build() { - OkHttpClient.Builder httpClientBuilder = - this.httpClient != null ? this.httpClient.newBuilder() : new OkHttpClient.Builder(); - - if (this.httpClient != null) { - timeout.ifPresent(timeout -> httpClientBuilder - .callTimeout(timeout, TimeUnit.SECONDS) - .connectTimeout(0, TimeUnit.SECONDS) - .writeTimeout(0, TimeUnit.SECONDS) - .readTimeout(0, TimeUnit.SECONDS)); - } else { - httpClientBuilder - .callTimeout(this.timeout.orElse(60), TimeUnit.SECONDS) - .connectTimeout(0, TimeUnit.SECONDS) - .writeTimeout(0, TimeUnit.SECONDS) - .readTimeout(0, TimeUnit.SECONDS) - .addInterceptor(new RetryInterceptor(this.maxRetries)); - } - - this.httpClient = httpClientBuilder.build(); - this.timeout = Optional.of(httpClient.callTimeoutMillis() / 1000); - - return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout.get()); - } - - /** - * Create a new Builder initialized with values from an existing ClientOptions - */ - public static Builder from(ClientOptions clientOptions) { - Builder builder = new Builder(); - builder.environment = clientOptions.environment(); - builder.timeout = Optional.of(clientOptions.timeout(null)); - builder.httpClient = clientOptions.httpClient(); - return builder; + OkHttpClient okhttpClient = new OkHttpClient.Builder() + .addInterceptor(new RetryInterceptor(3)) + .build(); + return new ClientOptions(environment, headers, headerSuppliers, okhttpClient); } } } diff --git a/src/main/java/com/cohere/api/core/CohereApiException.java b/src/main/java/com/cohere/api/core/CohereApiException.java index 46c8bb9..c3f60b6 100644 --- a/src/main/java/com/cohere/api/core/CohereApiException.java +++ b/src/main/java/com/cohere/api/core/CohereApiException.java @@ -3,12 +3,6 @@ */ package com.cohere.api.core; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import okhttp3.Response; - /** * This exception type will be thrown for any non-2XX API responses. */ @@ -23,25 +17,10 @@ public class CohereApiException extends CohereException { */ private final Object body; - private final Map> headers; - public CohereApiException(String message, int statusCode, Object body) { super(message); this.statusCode = statusCode; this.body = body; - this.headers = new HashMap<>(); - } - - public CohereApiException(String message, int statusCode, Object body, Response rawResponse) { - super(message); - this.statusCode = statusCode; - this.body = body; - this.headers = new HashMap<>(); - rawResponse.headers().forEach(header -> { - String key = header.component1(); - String value = header.component2(); - this.headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); - }); } /** @@ -58,13 +37,6 @@ public Object body() { return this.body; } - /** - * @return the headers - */ - public Map> headers() { - return this.headers; - } - @java.lang.Override public String toString() { return "CohereApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + body diff --git a/src/main/java/com/cohere/api/core/CohereHttpResponse.java b/src/main/java/com/cohere/api/core/CohereHttpResponse.java deleted file mode 100644 index 8518c92..0000000 --- a/src/main/java/com/cohere/api/core/CohereHttpResponse.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.core; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import okhttp3.Response; - -public final class CohereHttpResponse { - - private final T body; - - private final Map> headers; - - public CohereHttpResponse(T body, Response rawResponse) { - this.body = body; - - Map> headers = new HashMap<>(); - rawResponse.headers().forEach(header -> { - String key = header.component1(); - String value = header.component2(); - headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); - }); - this.headers = headers; - } - - public T body() { - return this.body; - } - - public Map> headers() { - return headers; - } -} diff --git a/src/main/java/com/cohere/api/core/InputStreamRequestBody.java b/src/main/java/com/cohere/api/core/InputStreamRequestBody.java index 9c141b5..cdc9a13 100644 --- a/src/main/java/com/cohere/api/core/InputStreamRequestBody.java +++ b/src/main/java/com/cohere/api/core/InputStreamRequestBody.java @@ -8,6 +8,7 @@ import java.util.Objects; import okhttp3.MediaType; import okhttp3.RequestBody; +import okhttp3.internal.Util; import okio.BufferedSink; import okio.Okio; import okio.Source; @@ -67,8 +68,12 @@ public long contentLength() throws IOException { */ @Override public void writeTo(BufferedSink sink) throws IOException { - try (Source source = Okio.source(inputStream)) { + Source source = null; + try { + source = Okio.source(inputStream); sink.writeAll(source); + } finally { + Util.closeQuietly(Objects.requireNonNull(source)); } } } diff --git a/src/main/java/com/cohere/api/core/Nullable.java b/src/main/java/com/cohere/api/core/Nullable.java deleted file mode 100644 index 1a50d35..0000000 --- a/src/main/java/com/cohere/api/core/Nullable.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.core; - -import java.util.Optional; -import java.util.function.Function; - -public final class Nullable { - - private final Either, Null> value; - - private Nullable() { - this.value = Either.left(Optional.empty()); - } - - private Nullable(T value) { - if (value == null) { - this.value = Either.right(Null.INSTANCE); - } else { - this.value = Either.left(Optional.of(value)); - } - } - - public static Nullable ofNull() { - return new Nullable<>(null); - } - - public static Nullable of(T value) { - return new Nullable<>(value); - } - - public static Nullable empty() { - return new Nullable<>(); - } - - public static Nullable ofOptional(Optional value) { - if (value.isPresent()) { - return of(value.get()); - } else { - return empty(); - } - } - - public boolean isNull() { - return this.value.isRight(); - } - - public boolean isEmpty() { - return this.value.isLeft() && !this.value.getLeft().isPresent(); - } - - public T get() { - if (this.isNull()) { - return null; - } - - return this.value.getLeft().get(); - } - - public Nullable map(Function mapper) { - if (this.isNull()) { - return Nullable.ofNull(); - } - - return Nullable.ofOptional(this.value.getLeft().map(mapper)); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof Nullable)) { - return false; - } - - if (((Nullable) other).isNull() && this.isNull()) { - return true; - } - - return this.value.getLeft().equals(((Nullable) other).value.getLeft()); - } - - private static final class Either { - private L left = null; - private R right = null; - - private Either(L left, R right) { - if (left != null && right != null) { - throw new IllegalArgumentException("Left and right argument cannot both be non-null."); - } - - if (left == null && right == null) { - throw new IllegalArgumentException("Left and right argument cannot both be null."); - } - - if (left != null) { - this.left = left; - } - - if (right != null) { - this.right = right; - } - } - - public static Either left(L left) { - return new Either<>(left, null); - } - - public static Either right(R right) { - return new Either<>(null, right); - } - - public boolean isLeft() { - return this.left != null; - } - - public boolean isRight() { - return this.right != null; - } - - public L getLeft() { - if (!this.isLeft()) { - throw new IllegalArgumentException("Cannot get left from right Either."); - } - return this.left; - } - - public R getRight() { - if (!this.isRight()) { - throw new IllegalArgumentException("Cannot get right from left Either."); - } - return this.right; - } - } - - private static final class Null { - private static final Null INSTANCE = new Null(); - - private Null() {} - } -} diff --git a/src/main/java/com/cohere/api/core/NullableNonemptyFilter.java b/src/main/java/com/cohere/api/core/NullableNonemptyFilter.java deleted file mode 100644 index 62644da..0000000 --- a/src/main/java/com/cohere/api/core/NullableNonemptyFilter.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.core; - -import java.util.Optional; - -public final class NullableNonemptyFilter { - @Override - public boolean equals(Object o) { - boolean isOptionalEmpty = isOptionalEmpty(o); - - return isOptionalEmpty; - } - - private boolean isOptionalEmpty(Object o) { - return o instanceof Optional && !((Optional) o).isPresent(); - } -} diff --git a/src/main/java/com/cohere/api/core/QueryStringMapper.java b/src/main/java/com/cohere/api/core/QueryStringMapper.java deleted file mode 100644 index a28f971..0000000 --- a/src/main/java/com/cohere/api/core/QueryStringMapper.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.core; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import okhttp3.HttpUrl; -import okhttp3.MultipartBody; - -public class QueryStringMapper { - - private static final ObjectMapper MAPPER = ObjectMappers.JSON_MAPPER; - - public static void addQueryParameter(HttpUrl.Builder httpUrl, String key, Object value, boolean arraysAsRepeats) { - JsonNode valueNode = MAPPER.valueToTree(value); - - List> flat; - if (valueNode.isObject()) { - flat = flattenObject((ObjectNode) valueNode, arraysAsRepeats); - } else if (valueNode.isArray()) { - flat = flattenArray((ArrayNode) valueNode, "", arraysAsRepeats); - } else { - if (valueNode.isTextual()) { - httpUrl.addQueryParameter(key, valueNode.textValue()); - } else { - httpUrl.addQueryParameter(key, valueNode.toString()); - } - return; - } - - for (Map.Entry field : flat) { - if (field.getValue().isTextual()) { - httpUrl.addQueryParameter(key + field.getKey(), field.getValue().textValue()); - } else { - httpUrl.addQueryParameter(key + field.getKey(), field.getValue().toString()); - } - } - } - - public static void addFormDataPart( - MultipartBody.Builder multipartBody, String key, Object value, boolean arraysAsRepeats) { - JsonNode valueNode = MAPPER.valueToTree(value); - - List> flat; - if (valueNode.isObject()) { - flat = flattenObject((ObjectNode) valueNode, arraysAsRepeats); - } else if (valueNode.isArray()) { - flat = flattenArray((ArrayNode) valueNode, "", arraysAsRepeats); - } else { - if (valueNode.isTextual()) { - multipartBody.addFormDataPart(key, valueNode.textValue()); - } else { - multipartBody.addFormDataPart(key, valueNode.toString()); - } - return; - } - - for (Map.Entry field : flat) { - if (field.getValue().isTextual()) { - multipartBody.addFormDataPart( - key + field.getKey(), field.getValue().textValue()); - } else { - multipartBody.addFormDataPart( - key + field.getKey(), field.getValue().toString()); - } - } - } - - public static List> flattenObject(ObjectNode object, boolean arraysAsRepeats) { - List> flat = new ArrayList<>(); - - Iterator> fields = object.fields(); - while (fields.hasNext()) { - Map.Entry field = fields.next(); - - String key = "[" + field.getKey() + "]"; - - if (field.getValue().isObject()) { - List> flatField = - flattenObject((ObjectNode) field.getValue(), arraysAsRepeats); - addAll(flat, flatField, key); - } else if (field.getValue().isArray()) { - List> flatField = - flattenArray((ArrayNode) field.getValue(), key, arraysAsRepeats); - addAll(flat, flatField, ""); - } else { - flat.add(new AbstractMap.SimpleEntry<>(key, field.getValue())); - } - } - - return flat; - } - - private static List> flattenArray( - ArrayNode array, String key, boolean arraysAsRepeats) { - List> flat = new ArrayList<>(); - - Iterator elements = array.elements(); - - int index = 0; - while (elements.hasNext()) { - JsonNode element = elements.next(); - - String indexKey = key + "[" + index + "]"; - - if (arraysAsRepeats) { - indexKey = key; - } - - if (element.isObject()) { - List> flatField = flattenObject((ObjectNode) element, arraysAsRepeats); - addAll(flat, flatField, indexKey); - } else if (element.isArray()) { - List> flatField = flattenArray((ArrayNode) element, "", arraysAsRepeats); - addAll(flat, flatField, indexKey); - } else { - flat.add(new AbstractMap.SimpleEntry<>(indexKey, element)); - } - - index++; - } - - return flat; - } - - private static void addAll( - List> target, List> source, String prefix) { - for (Map.Entry entry : source) { - Map.Entry entryToAdd = - new AbstractMap.SimpleEntry<>(prefix + entry.getKey(), entry.getValue()); - target.add(entryToAdd); - } - } -} diff --git a/src/main/java/com/cohere/api/core/RequestOptions.java b/src/main/java/com/cohere/api/core/RequestOptions.java index fa9e403..d88c8e9 100644 --- a/src/main/java/com/cohere/api/core/RequestOptions.java +++ b/src/main/java/com/cohere/api/core/RequestOptions.java @@ -7,7 +7,6 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; public final class RequestOptions { private final String token; @@ -18,23 +17,11 @@ public final class RequestOptions { private final TimeUnit timeoutTimeUnit; - private final Map headers; - - private final Map> headerSuppliers; - - private RequestOptions( - String token, - String clientName, - Optional timeout, - TimeUnit timeoutTimeUnit, - Map headers, - Map> headerSuppliers) { + private RequestOptions(String token, String clientName, Optional timeout, TimeUnit timeoutTimeUnit) { this.token = token; this.clientName = clientName; this.timeout = timeout; this.timeoutTimeUnit = timeoutTimeUnit; - this.headers = headers; - this.headerSuppliers = headerSuppliers; } public Optional getTimeout() { @@ -53,10 +40,6 @@ public Map getHeaders() { if (this.clientName != null) { headers.put("X-Client-Name", this.clientName); } - headers.putAll(this.headers); - this.headerSuppliers.forEach((key, supplier) -> { - headers.put(key, supplier.get()); - }); return headers; } @@ -64,7 +47,7 @@ public static Builder builder() { return new Builder(); } - public static class Builder { + public static final class Builder { private String token = null; private String clientName = null; @@ -73,10 +56,6 @@ public static class Builder { private TimeUnit timeoutTimeUnit = TimeUnit.SECONDS; - private final Map headers = new HashMap<>(); - - private final Map> headerSuppliers = new HashMap<>(); - public Builder token(String token) { this.token = token; return this; @@ -98,18 +77,8 @@ public Builder timeout(Integer timeout, TimeUnit timeoutTimeUnit) { return this; } - public Builder addHeader(String key, String value) { - this.headers.put(key, value); - return this; - } - - public Builder addHeader(String key, Supplier value) { - this.headerSuppliers.put(key, value); - return this; - } - public RequestOptions build() { - return new RequestOptions(token, clientName, timeout, timeoutTimeUnit, headers, headerSuppliers); + return new RequestOptions(token, clientName, timeout, timeoutTimeUnit); } } } diff --git a/src/main/java/com/cohere/api/core/RetryInterceptor.java b/src/main/java/com/cohere/api/core/RetryInterceptor.java index 5b17329..97336fa 100644 --- a/src/main/java/com/cohere/api/core/RetryInterceptor.java +++ b/src/main/java/com/cohere/api/core/RetryInterceptor.java @@ -52,7 +52,7 @@ private Response retryChain(Response response, Chain chain) throws IOException { } private static boolean shouldRetry(int statusCode) { - return statusCode == 408 || statusCode == 429 || statusCode >= 500; + return statusCode == 408 || statusCode == 409 || statusCode == 429 || statusCode >= 500; } private final class ExponentialBackoff { diff --git a/src/main/java/com/cohere/api/core/Stream.java b/src/main/java/com/cohere/api/core/Stream.java index 9b1c240..6309a2e 100644 --- a/src/main/java/com/cohere/api/core/Stream.java +++ b/src/main/java/com/cohere/api/core/Stream.java @@ -3,41 +3,29 @@ */ package com.cohere.api.core; -import java.io.Closeable; -import java.io.IOException; import java.io.Reader; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Scanner; /** - * The {@code Stream} class implements {@link Iterable} to provide a simple mechanism for reading and parsing + * The {@code Stream} class implmenets {@link Iterable} to provide a simple mechanism for reading and parsing * objects of a given type from data streamed via a {@link Reader} using a specified delimiter. *

* {@code Stream} assumes that data is being pushed to the provided {@link Reader} asynchronously and utilizes a * {@code Scanner} to block during iteration if the next object is not available. - * Iterable stream for parsing JSON and Server-Sent Events (SSE) data. - * Supports both newline-delimited JSON and SSE with optional stream termination. * * @param The type of objects in the stream. */ -public final class Stream implements Iterable, Closeable { - - private static final String NEWLINE = "\n"; - private static final String DATA_PREFIX = "data:"; - - public enum StreamType { - JSON, - SSE - } - +public final class Stream implements Iterable { + /** + * The {@link Class} of the objects in the stream. + */ private final Class valueType; + /** + * The {@link Scanner} used for reading from the input stream and blocking when neede during iteration. + */ private final Scanner scanner; - private final StreamType streamType; - private final String messageTerminator; - private final String streamTerminator; - private final Reader sseReader; - private boolean isClosed = false; /** * Constructs a new {@code Stream} with the specified value type, reader, and delimiter. @@ -47,61 +35,8 @@ public enum StreamType { * @param delimiter The delimiter used to separate elements in the stream. */ public Stream(Class valueType, Reader reader, String delimiter) { - this.valueType = valueType; this.scanner = new Scanner(reader).useDelimiter(delimiter); - this.streamType = StreamType.JSON; - this.messageTerminator = delimiter; - this.streamTerminator = null; - this.sseReader = null; - } - - private Stream(Class valueType, StreamType type, Reader reader, String terminator) { this.valueType = valueType; - this.streamType = type; - if (type == StreamType.JSON) { - this.scanner = new Scanner(reader).useDelimiter(terminator); - this.messageTerminator = terminator; - this.streamTerminator = null; - this.sseReader = null; - } else { - this.scanner = null; - this.messageTerminator = NEWLINE; - this.streamTerminator = terminator; - this.sseReader = reader; - } - } - - public static Stream fromJson(Class valueType, Reader reader, String delimiter) { - return new Stream<>(valueType, reader, delimiter); - } - - public static Stream fromJson(Class valueType, Reader reader) { - return new Stream<>(valueType, reader, NEWLINE); - } - - public static Stream fromSse(Class valueType, Reader sseReader) { - return new Stream<>(valueType, StreamType.SSE, sseReader, null); - } - - public static Stream fromSse(Class valueType, Reader sseReader, String streamTerminator) { - return new Stream<>(valueType, StreamType.SSE, sseReader, streamTerminator); - } - - @Override - public void close() throws IOException { - if (!isClosed) { - isClosed = true; - if (scanner != null) { - scanner.close(); - } - if (sseReader != null) { - sseReader.close(); - } - } - } - - private boolean isStreamClosed() { - return isClosed; } /** @@ -112,161 +47,51 @@ private boolean isStreamClosed() { */ @Override public Iterator iterator() { - if (streamType == StreamType.SSE) { - return new SSEIterator(); - } else { - return new JsonIterator(); - } - } - - private final class JsonIterator implements Iterator { - - /** - * Returns {@code true} if there are more elements in the stream. - *

- * Will block and wait for input if the stream has not ended and the next object is not yet available. - * - * @return {@code true} if there are more elements, {@code false} otherwise. - */ - @Override - public boolean hasNext() { - if (isStreamClosed()) { - return false; + return new Iterator() { + /** + * Returns {@code true} if there are more elements in the stream. + *

+ * Will block and wait for input if the stream has not ended and the next object is not yet available. + * + * @return {@code true} if there are more elements, {@code false} otherwise. + */ + @Override + public boolean hasNext() { + return scanner.hasNext(); } - return scanner.hasNext(); - } - /** - * Returns the next element in the stream. - *

- * Will block and wait for input if the stream has not ended and the next object is not yet available. - * - * @return The next element in the stream. - * @throws NoSuchElementException If there are no more elements in the stream. - */ - @Override - public T next() { - if (isStreamClosed()) { - throw new NoSuchElementException("Stream is closed"); - } - - if (!scanner.hasNext()) { - throw new NoSuchElementException(); - } else { - try { - T parsedResponse = - ObjectMappers.JSON_MAPPER.readValue(scanner.next().trim(), valueType); - return parsedResponse; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - - private final class SSEIterator implements Iterator { - private Scanner sseScanner; - private T nextItem; - private boolean hasNextItem = false; - private boolean endOfStream = false; - private StringBuilder buffer = new StringBuilder(); - private boolean prefixSeen = false; - - private SSEIterator() { - if (sseReader != null && !isStreamClosed()) { - this.sseScanner = new Scanner(sseReader); - } else { - this.endOfStream = true; - } - } - - @Override - public boolean hasNext() { - if (isStreamClosed() || endOfStream) { - return false; - } - - if (hasNextItem) { - return true; - } - - return readNextMessage(); - } - - @Override - public T next() { - if (!hasNext()) { - throw new NoSuchElementException("No more elements in stream"); - } - - T result = nextItem; - nextItem = null; - hasNextItem = false; - return result; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - private boolean readNextMessage() { - if (sseScanner == null || isStreamClosed()) { - endOfStream = true; - return false; - } - - 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; - } - - if (!prefixSeen && line.startsWith(DATA_PREFIX)) { - prefixSeen = true; - line = line.substring(DATA_PREFIX.length()).trim(); - } else if (!prefixSeen) { - continue; - } - - if (streamTerminator != null && line.contains(streamTerminator)) { - endOfStream = true; - return false; - } - - try { - nextItem = ObjectMappers.JSON_MAPPER.readValue(line, valueType); - hasNextItem = true; - prefixSeen = false; - return true; - } catch (Exception parseEx) { - continue; - } + /** + * Returns the next element in the stream. + *

+ * Will block and wait for input if the stream has not ended and the next object is not yet available. + * + * @return The next element in the stream. + * @throws NoSuchElementException If there are no more elements in the stream. + */ + @Override + public T next() { + if (!scanner.hasNext()) { + throw new NoSuchElementException(); + } else { + try { + T parsedResponse = ObjectMappers.JSON_MAPPER.readValue( + scanner.next().trim(), valueType); + return parsedResponse; + } catch (Exception e) { + throw new RuntimeException(e); } } + } - endOfStream = true; - return false; - - } catch (Exception e) { - System.err.println("Failed to parse SSE stream: " + e.getMessage()); - endOfStream = true; - return false; + /** + * Removing elements from {@code Stream} is not supported. + * + * @throws UnsupportedOperationException Always, as removal is not supported. + */ + @Override + public void remove() { + throw new UnsupportedOperationException(); } - } + }; } } diff --git a/src/main/java/com/cohere/api/errors/BadRequestError.java b/src/main/java/com/cohere/api/errors/BadRequestError.java index 60abf96..6546e91 100644 --- a/src/main/java/com/cohere/api/errors/BadRequestError.java +++ b/src/main/java/com/cohere/api/errors/BadRequestError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class BadRequestError extends CohereApiException { /** @@ -17,11 +16,6 @@ public BadRequestError(Object body) { this.body = body; } - public BadRequestError(Object body, Response rawResponse) { - super("BadRequestError", 400, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/ClientClosedRequestError.java b/src/main/java/com/cohere/api/errors/ClientClosedRequestError.java index cc78e15..89a0fc4 100644 --- a/src/main/java/com/cohere/api/errors/ClientClosedRequestError.java +++ b/src/main/java/com/cohere/api/errors/ClientClosedRequestError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class ClientClosedRequestError extends CohereApiException { /** @@ -17,11 +16,6 @@ public ClientClosedRequestError(Object body) { this.body = body; } - public ClientClosedRequestError(Object body, Response rawResponse) { - super("ClientClosedRequestError", 499, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/ForbiddenError.java b/src/main/java/com/cohere/api/errors/ForbiddenError.java index a139acc..23c461b 100644 --- a/src/main/java/com/cohere/api/errors/ForbiddenError.java +++ b/src/main/java/com/cohere/api/errors/ForbiddenError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class ForbiddenError extends CohereApiException { /** @@ -17,11 +16,6 @@ public ForbiddenError(Object body) { this.body = body; } - public ForbiddenError(Object body, Response rawResponse) { - super("ForbiddenError", 403, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/GatewayTimeoutError.java b/src/main/java/com/cohere/api/errors/GatewayTimeoutError.java index 3e28c9d..bf513ef 100644 --- a/src/main/java/com/cohere/api/errors/GatewayTimeoutError.java +++ b/src/main/java/com/cohere/api/errors/GatewayTimeoutError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class GatewayTimeoutError extends CohereApiException { /** @@ -17,11 +16,6 @@ public GatewayTimeoutError(Object body) { this.body = body; } - public GatewayTimeoutError(Object body, Response rawResponse) { - super("GatewayTimeoutError", 504, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/InternalServerError.java b/src/main/java/com/cohere/api/errors/InternalServerError.java index 3e5fbdb..5a64c17 100644 --- a/src/main/java/com/cohere/api/errors/InternalServerError.java +++ b/src/main/java/com/cohere/api/errors/InternalServerError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class InternalServerError extends CohereApiException { /** @@ -17,11 +16,6 @@ public InternalServerError(Object body) { this.body = body; } - public InternalServerError(Object body, Response rawResponse) { - super("InternalServerError", 500, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/InvalidTokenError.java b/src/main/java/com/cohere/api/errors/InvalidTokenError.java index eb1caa1..b889d1b 100644 --- a/src/main/java/com/cohere/api/errors/InvalidTokenError.java +++ b/src/main/java/com/cohere/api/errors/InvalidTokenError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class InvalidTokenError extends CohereApiException { /** @@ -17,11 +16,6 @@ public InvalidTokenError(Object body) { this.body = body; } - public InvalidTokenError(Object body, Response rawResponse) { - super("InvalidTokenError", 498, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/NotFoundError.java b/src/main/java/com/cohere/api/errors/NotFoundError.java index 6ec9e4c..37f7e9d 100644 --- a/src/main/java/com/cohere/api/errors/NotFoundError.java +++ b/src/main/java/com/cohere/api/errors/NotFoundError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class NotFoundError extends CohereApiException { /** @@ -17,11 +16,6 @@ public NotFoundError(Object body) { this.body = body; } - public NotFoundError(Object body, Response rawResponse) { - super("NotFoundError", 404, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/NotImplementedError.java b/src/main/java/com/cohere/api/errors/NotImplementedError.java index dc436b9..7ada371 100644 --- a/src/main/java/com/cohere/api/errors/NotImplementedError.java +++ b/src/main/java/com/cohere/api/errors/NotImplementedError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class NotImplementedError extends CohereApiException { /** @@ -17,11 +16,6 @@ public NotImplementedError(Object body) { this.body = body; } - public NotImplementedError(Object body, Response rawResponse) { - super("NotImplementedError", 501, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/ServiceUnavailableError.java b/src/main/java/com/cohere/api/errors/ServiceUnavailableError.java index 95dbf3e..a615b11 100644 --- a/src/main/java/com/cohere/api/errors/ServiceUnavailableError.java +++ b/src/main/java/com/cohere/api/errors/ServiceUnavailableError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class ServiceUnavailableError extends CohereApiException { /** @@ -17,11 +16,6 @@ public ServiceUnavailableError(Object body) { this.body = body; } - public ServiceUnavailableError(Object body, Response rawResponse) { - super("ServiceUnavailableError", 503, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/TooManyRequestsError.java b/src/main/java/com/cohere/api/errors/TooManyRequestsError.java index bbff67a..d1f4f4b 100644 --- a/src/main/java/com/cohere/api/errors/TooManyRequestsError.java +++ b/src/main/java/com/cohere/api/errors/TooManyRequestsError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class TooManyRequestsError extends CohereApiException { /** @@ -17,11 +16,6 @@ public TooManyRequestsError(Object body) { this.body = body; } - public TooManyRequestsError(Object body, Response rawResponse) { - super("TooManyRequestsError", 429, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/UnauthorizedError.java b/src/main/java/com/cohere/api/errors/UnauthorizedError.java index cb6815d..6a3df32 100644 --- a/src/main/java/com/cohere/api/errors/UnauthorizedError.java +++ b/src/main/java/com/cohere/api/errors/UnauthorizedError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class UnauthorizedError extends CohereApiException { /** @@ -17,11 +16,6 @@ public UnauthorizedError(Object body) { this.body = body; } - public UnauthorizedError(Object body, Response rawResponse) { - super("UnauthorizedError", 401, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/errors/UnprocessableEntityError.java b/src/main/java/com/cohere/api/errors/UnprocessableEntityError.java index 83fa51f..96d95e1 100644 --- a/src/main/java/com/cohere/api/errors/UnprocessableEntityError.java +++ b/src/main/java/com/cohere/api/errors/UnprocessableEntityError.java @@ -4,7 +4,6 @@ package com.cohere.api.errors; import com.cohere.api.core.CohereApiException; -import okhttp3.Response; public final class UnprocessableEntityError extends CohereApiException { /** @@ -17,11 +16,6 @@ public UnprocessableEntityError(Object body) { this.body = body; } - public UnprocessableEntityError(Object body, Response rawResponse) { - super("UnprocessableEntityError", 422, body, rawResponse); - this.body = body; - } - /** * @return the body */ diff --git a/src/main/java/com/cohere/api/requests/ChatRequest.java b/src/main/java/com/cohere/api/requests/ChatRequest.java index 5c4e8d7..4125d21 100644 --- a/src/main/java/com/cohere/api/requests/ChatRequest.java +++ b/src/main/java/com/cohere/api/requests/ChatRequest.java @@ -70,6 +70,10 @@ public final class ChatRequest { private final Optional presencePenalty; + private final Optional rawPrompting; + + private final Optional returnPrompt; + private final Optional> tools; private final Optional> toolResults; @@ -103,6 +107,8 @@ private ChatRequest( Optional> stopSequences, Optional frequencyPenalty, Optional presencePenalty, + Optional rawPrompting, + Optional returnPrompt, Optional> tools, Optional> toolResults, Optional forceSingleStep, @@ -129,6 +135,8 @@ private ChatRequest( this.stopSequences = stopSequences; this.frequencyPenalty = frequencyPenalty; this.presencePenalty = presencePenalty; + this.rawPrompting = rawPrompting; + this.returnPrompt = returnPrompt; this.tools = tools; this.toolResults = toolResults; this.forceSingleStep = forceSingleStep; @@ -363,6 +371,24 @@ public Optional getPresencePenalty() { return presencePenalty; } + /** + * @return When enabled, the user's prompt will be sent to the model without + * any pre-processing. + *

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

+ */ + @JsonProperty("raw_prompting") + public Optional getRawPrompting() { + return rawPrompting; + } + + /** + * @return The prompt is returned in the prompt response field when this is enabled. + */ + @JsonProperty("return_prompt") + public Optional getReturnPrompt() { + return returnPrompt; + } + /** * @return A list of available tools (functions) that the model may suggest invoking before producing a text response. *

When tools is passed (without tool_results), the text field in the response will be "" and the tool_calls field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the tool_calls array will be empty.

@@ -458,6 +484,8 @@ private boolean equalTo(ChatRequest other) { && stopSequences.equals(other.stopSequences) && frequencyPenalty.equals(other.frequencyPenalty) && presencePenalty.equals(other.presencePenalty) + && rawPrompting.equals(other.rawPrompting) + && returnPrompt.equals(other.returnPrompt) && tools.equals(other.tools) && toolResults.equals(other.toolResults) && forceSingleStep.equals(other.forceSingleStep) @@ -488,6 +516,8 @@ public int hashCode() { this.stopSequences, this.frequencyPenalty, this.presencePenalty, + this.rawPrompting, + this.returnPrompt, this.tools, this.toolResults, this.forceSingleStep, @@ -505,10 +535,6 @@ public static MessageStage builder() { } public interface MessageStage { - /** - *

Text input for the model to respond to.

- *

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

- */ _FinalStage message(@NotNull String message); Builder from(ChatRequest other); @@ -517,231 +543,98 @@ public interface MessageStage { public interface _FinalStage { ChatRequest build(); - /** - *

Pass text/event-stream to receive the streamed response as server-sent events. The default is \n delimited events.

- */ _FinalStage accepts(Optional accepts); _FinalStage accepts(String accepts); - /** - *

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

- *

Compatible Deployments: Cohere Platform, Private Deployments

- */ _FinalStage model(Optional model); _FinalStage model(String model); - /** - *

When specified, the default Cohere preamble will be replaced with the provided one. Preambles are a part of the prompt used to adjust the model's overall behavior and conversation style, and use the SYSTEM role.

- *

The SYSTEM role is also used for the contents of the optional chat_history= parameter. When used with the chat_history= parameter it adds content throughout a conversation. Conversely, when used with the preamble= parameter it adds content at the start of the conversation only.

- *

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

- */ _FinalStage preamble(Optional preamble); _FinalStage preamble(String preamble); - /** - *

A list of previous messages between the user and the model, giving the model conversational context for responding to the user's message.

- *

Each item represents a single message in the chat history, excluding the current user turn. It has two properties: role and message. The role identifies the sender (CHATBOT, SYSTEM, or USER), while the message contains the text content.

- *

The chat_history parameter should not be used for SYSTEM messages in most cases. Instead, to add a SYSTEM role message at the beginning of a conversation, the preamble parameter should be used.

- *

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

- */ _FinalStage chatHistory(Optional> chatHistory); _FinalStage chatHistory(List chatHistory); - /** - *

An alternative to chat_history.

- *

Providing a conversation_id creates or resumes a persisted conversation with the specified ID. The ID can be any non empty string.

- *

Compatible Deployments: Cohere Platform

- */ _FinalStage conversationId(Optional conversationId); _FinalStage conversationId(String conversationId); - /** - *

Defaults to AUTO when connectors are specified and OFF in all other cases.

- *

Dictates how the prompt will be constructed.

- *

With prompt_truncation set to "AUTO", some elements from chat_history and documents will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be changed and ranked by relevance.

- *

With prompt_truncation set to "AUTO_PRESERVE_ORDER", some elements from chat_history and documents will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be preserved as they are inputted into the API.

- *

With prompt_truncation set to "OFF", no elements will be dropped. If the sum of the inputs exceeds the model's context length limit, a TooManyTokens error will be returned.

- *

Compatible Deployments:

- *
    - *
  • AUTO: Cohere Platform Only
  • - *
  • AUTO_PRESERVE_ORDER: Azure, AWS Sagemaker/Bedrock, Private Deployments
  • - *
- */ _FinalStage promptTruncation(Optional promptTruncation); _FinalStage promptTruncation(ChatRequestPromptTruncation promptTruncation); - /** - *

Accepts {"id": "web-search"}, and/or the "id" for a custom connector, if you've created one.

- *

When specified, the model's reply will be enriched with information found by querying each of the connectors (RAG).

- *

Compatible Deployments: Cohere Platform

- */ _FinalStage connectors(Optional> connectors); _FinalStage connectors(List connectors); - /** - *

Defaults to false.

- *

When true, the response will only contain a list of generated search queries, but no search will take place, and no reply from the model to the user's message will be generated.

- *

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

- */ _FinalStage searchQueriesOnly(Optional searchQueriesOnly); _FinalStage searchQueriesOnly(Boolean searchQueriesOnly); - /** - *

A list of relevant documents that the model can cite to generate a more accurate reply. Each document is a string-string dictionary.

- *

Example:

- *
[
-         *   { "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
-         *   { "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica." },
-         * ]
-         * 
- *

Keys and values from each document will be serialized to a string and passed to the model. The resulting generation will include citations that reference some of these documents.

- *

Some suggested keys are "text", "author", and "date". For better generation quality, it is recommended to keep the total word count of the strings in the dictionary to under 300 words.

- *

An id field (string) can be optionally supplied to identify the document in the citations. This field will not be passed to the model.

- *

An _excludes field (array of strings) can be optionally supplied to omit some key-value pairs from being shown to the model. The omitted fields will still show up in the citation object. The "_excludes" field will not be passed to the model.

- *

See 'Document Mode' in the guide for more information.

- *

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

- */ _FinalStage documents(Optional>> documents); _FinalStage documents(List> documents); - /** - *

Defaults to "accurate".

- *

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

- *

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

- */ _FinalStage citationQuality(Optional citationQuality); _FinalStage citationQuality(ChatRequestCitationQuality citationQuality); - /** - *

Defaults to 0.3.

- *

A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.

- *

Randomness can be further maximized by increasing the value of the p parameter.

- *

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

- */ _FinalStage temperature(Optional temperature); _FinalStage temperature(Float temperature); - /** - *

The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.

- *

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

- */ _FinalStage maxTokens(Optional maxTokens); _FinalStage maxTokens(Integer maxTokens); - /** - *

The maximum number of input tokens to send to the model. If not specified, max_input_tokens is the model's context length limit minus a small buffer.

- *

Input will be truncated according to the prompt_truncation parameter.

- *

Compatible Deployments: Cohere Platform

- */ _FinalStage maxInputTokens(Optional maxInputTokens); _FinalStage maxInputTokens(Integer maxInputTokens); - /** - *

Ensures only the top k most likely tokens are considered for generation at each step. - * Defaults to 0, min value of 0, max value of 500.

- *

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

- */ _FinalStage k(Optional k); _FinalStage k(Integer k); - /** - *

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.

- *

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

- */ _FinalStage p(Optional p); _FinalStage p(Double p); - /** - *

If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed.

- *

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

- */ _FinalStage seed(Optional seed); _FinalStage seed(Integer seed); - /** - *

A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.

- *

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

- */ _FinalStage stopSequences(Optional> stopSequences); _FinalStage stopSequences(List stopSequences); - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

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.

- *

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

- */ _FinalStage frequencyPenalty(Optional frequencyPenalty); _FinalStage frequencyPenalty(Double frequencyPenalty); - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

- *

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

- */ _FinalStage presencePenalty(Optional presencePenalty); _FinalStage presencePenalty(Double presencePenalty); - /** - *

A list of available tools (functions) that the model may suggest invoking before producing a text response.

- *

When tools is passed (without tool_results), the text field in the response will be "" and the tool_calls field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the tool_calls array will be empty.

- *

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

- */ + _FinalStage rawPrompting(Optional rawPrompting); + + _FinalStage rawPrompting(Boolean rawPrompting); + + _FinalStage returnPrompt(Optional returnPrompt); + + _FinalStage returnPrompt(Boolean returnPrompt); + _FinalStage tools(Optional> tools); _FinalStage tools(List tools); - /** - *

A list of results from invoking tools recommended by the model in the previous chat turn. Results are used to produce a text response and will be referenced in citations. When using tool_results, tools must be passed as well. - * Each tool_result contains information about how it was invoked, as well as a list of outputs in the form of dictionaries.

- *

Note: outputs must be a list of objects. If your tool returns a single object (eg {"status": 200}), make sure to wrap it in a list.

- *
tool_results = [
-         *   {
-         *     "call": {
-         *       "name": <tool name>,
-         *       "parameters": {
-         *         <param name>: <param value>
-         *       }
-         *     },
-         *     "outputs": [{
-         *       <key>: <value>
-         *     }]
-         *   },
-         *   ...
-         * ]
-         * 
- *

Note: Chat calls with tool_results should not be included in the Chat history to avoid duplication of the message text.

- *

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

- */ _FinalStage toolResults(Optional> toolResults); _FinalStage toolResults(List toolResults); - /** - *

Forces the chat to be single step. Defaults to false.

- */ _FinalStage forceSingleStep(Optional forceSingleStep); _FinalStage forceSingleStep(Boolean forceSingleStep); @@ -750,14 +643,6 @@ public interface _FinalStage { _FinalStage responseFormat(ResponseFormat responseFormat); - /** - *

Used to select the safety instruction inserted into the prompt. Defaults to CONTEXTUAL. - * When NONE is specified, the safety instruction will be omitted.

- *

Safety modes are not yet configurable in combination with tools, tool_results and documents parameters.

- *

Note: This parameter is only compatible newer Cohere models, starting with Command R 08-2024 and Command R+ 08-2024.

- *

Note: command-r7b-12-2024 and newer models only support "CONTEXTUAL" and "STRICT" modes.

- *

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

- */ _FinalStage safetyMode(Optional safetyMode); _FinalStage safetyMode(ChatRequestSafetyMode safetyMode); @@ -777,6 +662,10 @@ public static final class Builder implements MessageStage, _FinalStage { private Optional> tools = Optional.empty(); + private Optional returnPrompt = Optional.empty(); + + private Optional rawPrompting = Optional.empty(); + private Optional presencePenalty = Optional.empty(); private Optional frequencyPenalty = Optional.empty(); @@ -842,6 +731,8 @@ public Builder from(ChatRequest other) { stopSequences(other.getStopSequences()); frequencyPenalty(other.getFrequencyPenalty()); presencePenalty(other.getPresencePenalty()); + rawPrompting(other.getRawPrompting()); + returnPrompt(other.getReturnPrompt()); tools(other.getTools()); toolResults(other.getToolResults()); forceSingleStep(other.getForceSingleStep()); @@ -851,8 +742,6 @@ public Builder from(ChatRequest other) { } /** - *

Text input for the model to respond to.

- *

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

*

Text input for the model to respond to.

*

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

* @return Reference to {@code this} so that method calls can be chained together. @@ -879,14 +768,6 @@ public _FinalStage safetyMode(ChatRequestSafetyMode safetyMode) { return this; } - /** - *

Used to select the safety instruction inserted into the prompt. Defaults to CONTEXTUAL. - * When NONE is specified, the safety instruction will be omitted.

- *

Safety modes are not yet configurable in combination with tools, tool_results and documents parameters.

- *

Note: This parameter is only compatible newer Cohere models, starting with Command R 08-2024 and Command R+ 08-2024.

- *

Note: command-r7b-12-2024 and newer models only support "CONTEXTUAL" and "STRICT" modes.

- *

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

- */ @java.lang.Override @JsonSetter(value = "safety_mode", nulls = Nulls.SKIP) public _FinalStage safetyMode(Optional safetyMode) { @@ -917,9 +798,6 @@ public _FinalStage forceSingleStep(Boolean forceSingleStep) { return this; } - /** - *

Forces the chat to be single step. Defaults to false.

- */ @java.lang.Override @JsonSetter(value = "force_single_step", nulls = Nulls.SKIP) public _FinalStage forceSingleStep(Optional forceSingleStep) { @@ -956,28 +834,6 @@ public _FinalStage toolResults(List toolResults) { return this; } - /** - *

A list of results from invoking tools recommended by the model in the previous chat turn. Results are used to produce a text response and will be referenced in citations. When using tool_results, tools must be passed as well. - * Each tool_result contains information about how it was invoked, as well as a list of outputs in the form of dictionaries.

- *

Note: outputs must be a list of objects. If your tool returns a single object (eg {"status": 200}), make sure to wrap it in a list.

- *
tool_results = [
-         *   {
-         *     "call": {
-         *       "name": <tool name>,
-         *       "parameters": {
-         *         <param name>: <param value>
-         *       }
-         *     },
-         *     "outputs": [{
-         *       <key>: <value>
-         *     }]
-         *   },
-         *   ...
-         * ]
-         * 
- *

Note: Chat calls with tool_results should not be included in the Chat history to avoid duplication of the message text.

- *

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

- */ @java.lang.Override @JsonSetter(value = "tool_results", nulls = Nulls.SKIP) public _FinalStage toolResults(Optional> toolResults) { @@ -997,11 +853,6 @@ public _FinalStage tools(List tools) { return this; } - /** - *

A list of available tools (functions) that the model may suggest invoking before producing a text response.

- *

When tools is passed (without tool_results), the text field in the response will be "" and the tool_calls field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the tool_calls array will be empty.

- *

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

- */ @java.lang.Override @JsonSetter(value = "tools", nulls = Nulls.SKIP) public _FinalStage tools(Optional> tools) { @@ -1010,14 +861,38 @@ public _FinalStage tools(Optional> tools) { } /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

+ *

The prompt is returned in the prompt response field when this is enabled.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage returnPrompt(Boolean returnPrompt) { + this.returnPrompt = Optional.ofNullable(returnPrompt); + return this; + } + + @java.lang.Override + @JsonSetter(value = "return_prompt", nulls = Nulls.SKIP) + public _FinalStage returnPrompt(Optional returnPrompt) { + this.returnPrompt = returnPrompt; + return this; + } + + /** + *

When enabled, the user's prompt will be sent to the model without + * any pre-processing.

*

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

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage presencePenalty(Double presencePenalty) { - this.presencePenalty = Optional.ofNullable(presencePenalty); + public _FinalStage rawPrompting(Boolean rawPrompting) { + this.rawPrompting = Optional.ofNullable(rawPrompting); + return this; + } + + @java.lang.Override + @JsonSetter(value = "raw_prompting", nulls = Nulls.SKIP) + public _FinalStage rawPrompting(Optional rawPrompting) { + this.rawPrompting = rawPrompting; return this; } @@ -1025,7 +900,14 @@ public _FinalStage presencePenalty(Double presencePenalty) { *

Defaults to 0.0, min value of 0.0, max value of 1.0.

*

Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

*

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

+ * @return Reference to {@code this} so that method calls can be chained together. */ + @java.lang.Override + public _FinalStage presencePenalty(Double presencePenalty) { + this.presencePenalty = Optional.ofNullable(presencePenalty); + return this; + } + @java.lang.Override @JsonSetter(value = "presence_penalty", nulls = Nulls.SKIP) public _FinalStage presencePenalty(Optional presencePenalty) { @@ -1045,11 +927,6 @@ public _FinalStage frequencyPenalty(Double frequencyPenalty) { return this; } - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

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.

- *

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

- */ @java.lang.Override @JsonSetter(value = "frequency_penalty", nulls = Nulls.SKIP) public _FinalStage frequencyPenalty(Optional frequencyPenalty) { @@ -1068,10 +945,6 @@ public _FinalStage stopSequences(List stopSequences) { return this; } - /** - *

A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.

- *

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

- */ @java.lang.Override @JsonSetter(value = "stop_sequences", nulls = Nulls.SKIP) public _FinalStage stopSequences(Optional> stopSequences) { @@ -1093,13 +966,6 @@ public _FinalStage seed(Integer seed) { return this; } - /** - *

If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed.

- *

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

- */ @java.lang.Override @JsonSetter(value = "seed", nulls = Nulls.SKIP) public _FinalStage seed(Optional seed) { @@ -1119,11 +985,6 @@ public _FinalStage p(Double p) { return this; } - /** - *

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.

- *

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

- */ @java.lang.Override @JsonSetter(value = "p", nulls = Nulls.SKIP) public _FinalStage p(Optional p) { @@ -1143,11 +1004,6 @@ public _FinalStage k(Integer k) { return this; } - /** - *

Ensures only the top k most likely tokens are considered for generation at each step. - * Defaults to 0, min value of 0, max value of 500.

- *

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

- */ @java.lang.Override @JsonSetter(value = "k", nulls = Nulls.SKIP) public _FinalStage k(Optional k) { @@ -1167,11 +1023,6 @@ public _FinalStage maxInputTokens(Integer maxInputTokens) { return this; } - /** - *

The maximum number of input tokens to send to the model. If not specified, max_input_tokens is the model's context length limit minus a small buffer.

- *

Input will be truncated according to the prompt_truncation parameter.

- *

Compatible Deployments: Cohere Platform

- */ @java.lang.Override @JsonSetter(value = "max_input_tokens", nulls = Nulls.SKIP) public _FinalStage maxInputTokens(Optional maxInputTokens) { @@ -1190,10 +1041,6 @@ public _FinalStage maxTokens(Integer maxTokens) { return this; } - /** - *

The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.

- *

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

- */ @java.lang.Override @JsonSetter(value = "max_tokens", nulls = Nulls.SKIP) public _FinalStage maxTokens(Optional maxTokens) { @@ -1214,12 +1061,6 @@ public _FinalStage temperature(Float temperature) { return this; } - /** - *

Defaults to 0.3.

- *

A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.

- *

Randomness can be further maximized by increasing the value of the p parameter.

- *

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

- */ @java.lang.Override @JsonSetter(value = "temperature", nulls = Nulls.SKIP) public _FinalStage temperature(Optional temperature) { @@ -1239,11 +1080,6 @@ public _FinalStage citationQuality(ChatRequestCitationQuality citationQuality) { return this; } - /** - *

Defaults to "accurate".

- *

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

- *

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

- */ @java.lang.Override @JsonSetter(value = "citation_quality", nulls = Nulls.SKIP) public _FinalStage citationQuality(Optional citationQuality) { @@ -1273,21 +1109,6 @@ public _FinalStage documents(List> documents) { return this; } - /** - *

A list of relevant documents that the model can cite to generate a more accurate reply. Each document is a string-string dictionary.

- *

Example:

- *
[
-         *   { "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
-         *   { "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica." },
-         * ]
-         * 
- *

Keys and values from each document will be serialized to a string and passed to the model. The resulting generation will include citations that reference some of these documents.

- *

Some suggested keys are "text", "author", and "date". For better generation quality, it is recommended to keep the total word count of the strings in the dictionary to under 300 words.

- *

An id field (string) can be optionally supplied to identify the document in the citations. This field will not be passed to the model.

- *

An _excludes field (array of strings) can be optionally supplied to omit some key-value pairs from being shown to the model. The omitted fields will still show up in the citation object. The "_excludes" field will not be passed to the model.

- *

See 'Document Mode' in the guide for more information.

- *

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

- */ @java.lang.Override @JsonSetter(value = "documents", nulls = Nulls.SKIP) public _FinalStage documents(Optional>> documents) { @@ -1307,11 +1128,6 @@ public _FinalStage searchQueriesOnly(Boolean searchQueriesOnly) { return this; } - /** - *

Defaults to false.

- *

When true, the response will only contain a list of generated search queries, but no search will take place, and no reply from the model to the user's message will be generated.

- *

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

- */ @java.lang.Override @JsonSetter(value = "search_queries_only", nulls = Nulls.SKIP) public _FinalStage searchQueriesOnly(Optional searchQueriesOnly) { @@ -1331,11 +1147,6 @@ public _FinalStage connectors(List connectors) { return this; } - /** - *

Accepts {"id": "web-search"}, and/or the "id" for a custom connector, if you've created one.

- *

When specified, the model's reply will be enriched with information found by querying each of the connectors (RAG).

- *

Compatible Deployments: Cohere Platform

- */ @java.lang.Override @JsonSetter(value = "connectors", nulls = Nulls.SKIP) public _FinalStage connectors(Optional> connectors) { @@ -1362,18 +1173,6 @@ public _FinalStage promptTruncation(ChatRequestPromptTruncation promptTruncation return this; } - /** - *

Defaults to AUTO when connectors are specified and OFF in all other cases.

- *

Dictates how the prompt will be constructed.

- *

With prompt_truncation set to "AUTO", some elements from chat_history and documents will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be changed and ranked by relevance.

- *

With prompt_truncation set to "AUTO_PRESERVE_ORDER", some elements from chat_history and documents will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be preserved as they are inputted into the API.

- *

With prompt_truncation set to "OFF", no elements will be dropped. If the sum of the inputs exceeds the model's context length limit, a TooManyTokens error will be returned.

- *

Compatible Deployments:

- *
    - *
  • AUTO: Cohere Platform Only
  • - *
  • AUTO_PRESERVE_ORDER: Azure, AWS Sagemaker/Bedrock, Private Deployments
  • - *
- */ @java.lang.Override @JsonSetter(value = "prompt_truncation", nulls = Nulls.SKIP) public _FinalStage promptTruncation(Optional promptTruncation) { @@ -1393,11 +1192,6 @@ public _FinalStage conversationId(String conversationId) { return this; } - /** - *

An alternative to chat_history.

- *

Providing a conversation_id creates or resumes a persisted conversation with the specified ID. The ID can be any non empty string.

- *

Compatible Deployments: Cohere Platform

- */ @java.lang.Override @JsonSetter(value = "conversation_id", nulls = Nulls.SKIP) public _FinalStage conversationId(Optional conversationId) { @@ -1418,12 +1212,6 @@ public _FinalStage chatHistory(List chatHistory) { return this; } - /** - *

A list of previous messages between the user and the model, giving the model conversational context for responding to the user's message.

- *

Each item represents a single message in the chat history, excluding the current user turn. It has two properties: role and message. The role identifies the sender (CHATBOT, SYSTEM, or USER), while the message contains the text content.

- *

The chat_history parameter should not be used for SYSTEM messages in most cases. Instead, to add a SYSTEM role message at the beginning of a conversation, the preamble parameter should be used.

- *

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

- */ @java.lang.Override @JsonSetter(value = "chat_history", nulls = Nulls.SKIP) public _FinalStage chatHistory(Optional> chatHistory) { @@ -1443,11 +1231,6 @@ public _FinalStage preamble(String preamble) { return this; } - /** - *

When specified, the default Cohere preamble will be replaced with the provided one. Preambles are a part of the prompt used to adjust the model's overall behavior and conversation style, and use the SYSTEM role.

- *

The SYSTEM role is also used for the contents of the optional chat_history= parameter. When used with the chat_history= parameter it adds content throughout a conversation. Conversely, when used with the preamble= parameter it adds content at the start of the conversation only.

- *

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

- */ @java.lang.Override @JsonSetter(value = "preamble", nulls = Nulls.SKIP) public _FinalStage preamble(Optional preamble) { @@ -1466,10 +1249,6 @@ public _FinalStage model(String model) { return this; } - /** - *

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

- *

Compatible Deployments: Cohere Platform, Private Deployments

- */ @java.lang.Override @JsonSetter(value = "model", nulls = Nulls.SKIP) public _FinalStage model(Optional model) { @@ -1487,9 +1266,6 @@ public _FinalStage accepts(String accepts) { return this; } - /** - *

Pass text/event-stream to receive the streamed response as server-sent events. The default is \n delimited events.

- */ @java.lang.Override @JsonSetter(value = "Accepts", nulls = Nulls.SKIP) public _FinalStage accepts(Optional accepts) { @@ -1520,6 +1296,8 @@ public ChatRequest build() { stopSequences, frequencyPenalty, presencePenalty, + rawPrompting, + returnPrompt, tools, toolResults, forceSingleStep, diff --git a/src/main/java/com/cohere/api/requests/ChatStreamRequest.java b/src/main/java/com/cohere/api/requests/ChatStreamRequest.java index f3f1089..2a92ca1 100644 --- a/src/main/java/com/cohere/api/requests/ChatStreamRequest.java +++ b/src/main/java/com/cohere/api/requests/ChatStreamRequest.java @@ -70,6 +70,10 @@ public final class ChatStreamRequest { private final Optional presencePenalty; + private final Optional rawPrompting; + + private final Optional returnPrompt; + private final Optional> tools; private final Optional> toolResults; @@ -103,6 +107,8 @@ private ChatStreamRequest( Optional> stopSequences, Optional frequencyPenalty, Optional presencePenalty, + Optional rawPrompting, + Optional returnPrompt, Optional> tools, Optional> toolResults, Optional forceSingleStep, @@ -129,6 +135,8 @@ private ChatStreamRequest( this.stopSequences = stopSequences; this.frequencyPenalty = frequencyPenalty; this.presencePenalty = presencePenalty; + this.rawPrompting = rawPrompting; + this.returnPrompt = returnPrompt; this.tools = tools; this.toolResults = toolResults; this.forceSingleStep = forceSingleStep; @@ -363,6 +371,24 @@ public Optional getPresencePenalty() { return presencePenalty; } + /** + * @return When enabled, the user's prompt will be sent to the model without + * any pre-processing. + *

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

+ */ + @JsonProperty("raw_prompting") + public Optional getRawPrompting() { + return rawPrompting; + } + + /** + * @return The prompt is returned in the prompt response field when this is enabled. + */ + @JsonProperty("return_prompt") + public Optional getReturnPrompt() { + return returnPrompt; + } + /** * @return A list of available tools (functions) that the model may suggest invoking before producing a text response. *

When tools is passed (without tool_results), the text field in the response will be "" and the tool_calls field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the tool_calls array will be empty.

@@ -458,6 +484,8 @@ private boolean equalTo(ChatStreamRequest other) { && stopSequences.equals(other.stopSequences) && frequencyPenalty.equals(other.frequencyPenalty) && presencePenalty.equals(other.presencePenalty) + && rawPrompting.equals(other.rawPrompting) + && returnPrompt.equals(other.returnPrompt) && tools.equals(other.tools) && toolResults.equals(other.toolResults) && forceSingleStep.equals(other.forceSingleStep) @@ -488,6 +516,8 @@ public int hashCode() { this.stopSequences, this.frequencyPenalty, this.presencePenalty, + this.rawPrompting, + this.returnPrompt, this.tools, this.toolResults, this.forceSingleStep, @@ -505,10 +535,6 @@ public static MessageStage builder() { } public interface MessageStage { - /** - *

Text input for the model to respond to.

- *

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

- */ _FinalStage message(@NotNull String message); Builder from(ChatStreamRequest other); @@ -517,231 +543,98 @@ public interface MessageStage { public interface _FinalStage { ChatStreamRequest build(); - /** - *

Pass text/event-stream to receive the streamed response as server-sent events. The default is \n delimited events.

- */ _FinalStage accepts(Optional accepts); _FinalStage accepts(String accepts); - /** - *

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

- *

Compatible Deployments: Cohere Platform, Private Deployments

- */ _FinalStage model(Optional model); _FinalStage model(String model); - /** - *

When specified, the default Cohere preamble will be replaced with the provided one. Preambles are a part of the prompt used to adjust the model's overall behavior and conversation style, and use the SYSTEM role.

- *

The SYSTEM role is also used for the contents of the optional chat_history= parameter. When used with the chat_history= parameter it adds content throughout a conversation. Conversely, when used with the preamble= parameter it adds content at the start of the conversation only.

- *

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

- */ _FinalStage preamble(Optional preamble); _FinalStage preamble(String preamble); - /** - *

A list of previous messages between the user and the model, giving the model conversational context for responding to the user's message.

- *

Each item represents a single message in the chat history, excluding the current user turn. It has two properties: role and message. The role identifies the sender (CHATBOT, SYSTEM, or USER), while the message contains the text content.

- *

The chat_history parameter should not be used for SYSTEM messages in most cases. Instead, to add a SYSTEM role message at the beginning of a conversation, the preamble parameter should be used.

- *

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

- */ _FinalStage chatHistory(Optional> chatHistory); _FinalStage chatHistory(List chatHistory); - /** - *

An alternative to chat_history.

- *

Providing a conversation_id creates or resumes a persisted conversation with the specified ID. The ID can be any non empty string.

- *

Compatible Deployments: Cohere Platform

- */ _FinalStage conversationId(Optional conversationId); _FinalStage conversationId(String conversationId); - /** - *

Defaults to AUTO when connectors are specified and OFF in all other cases.

- *

Dictates how the prompt will be constructed.

- *

With prompt_truncation set to "AUTO", some elements from chat_history and documents will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be changed and ranked by relevance.

- *

With prompt_truncation set to "AUTO_PRESERVE_ORDER", some elements from chat_history and documents will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be preserved as they are inputted into the API.

- *

With prompt_truncation set to "OFF", no elements will be dropped. If the sum of the inputs exceeds the model's context length limit, a TooManyTokens error will be returned.

- *

Compatible Deployments:

- *
    - *
  • AUTO: Cohere Platform Only
  • - *
  • AUTO_PRESERVE_ORDER: Azure, AWS Sagemaker/Bedrock, Private Deployments
  • - *
- */ _FinalStage promptTruncation(Optional promptTruncation); _FinalStage promptTruncation(ChatStreamRequestPromptTruncation promptTruncation); - /** - *

Accepts {"id": "web-search"}, and/or the "id" for a custom connector, if you've created one.

- *

When specified, the model's reply will be enriched with information found by querying each of the connectors (RAG).

- *

Compatible Deployments: Cohere Platform

- */ _FinalStage connectors(Optional> connectors); _FinalStage connectors(List connectors); - /** - *

Defaults to false.

- *

When true, the response will only contain a list of generated search queries, but no search will take place, and no reply from the model to the user's message will be generated.

- *

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

- */ _FinalStage searchQueriesOnly(Optional searchQueriesOnly); _FinalStage searchQueriesOnly(Boolean searchQueriesOnly); - /** - *

A list of relevant documents that the model can cite to generate a more accurate reply. Each document is a string-string dictionary.

- *

Example:

- *
[
-         *   { "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
-         *   { "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica." },
-         * ]
-         * 
- *

Keys and values from each document will be serialized to a string and passed to the model. The resulting generation will include citations that reference some of these documents.

- *

Some suggested keys are "text", "author", and "date". For better generation quality, it is recommended to keep the total word count of the strings in the dictionary to under 300 words.

- *

An id field (string) can be optionally supplied to identify the document in the citations. This field will not be passed to the model.

- *

An _excludes field (array of strings) can be optionally supplied to omit some key-value pairs from being shown to the model. The omitted fields will still show up in the citation object. The "_excludes" field will not be passed to the model.

- *

See 'Document Mode' in the guide for more information.

- *

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

- */ _FinalStage documents(Optional>> documents); _FinalStage documents(List> documents); - /** - *

Defaults to "accurate".

- *

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

- *

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

- */ _FinalStage citationQuality(Optional citationQuality); _FinalStage citationQuality(ChatStreamRequestCitationQuality citationQuality); - /** - *

Defaults to 0.3.

- *

A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.

- *

Randomness can be further maximized by increasing the value of the p parameter.

- *

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

- */ _FinalStage temperature(Optional temperature); _FinalStage temperature(Float temperature); - /** - *

The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.

- *

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

- */ _FinalStage maxTokens(Optional maxTokens); _FinalStage maxTokens(Integer maxTokens); - /** - *

The maximum number of input tokens to send to the model. If not specified, max_input_tokens is the model's context length limit minus a small buffer.

- *

Input will be truncated according to the prompt_truncation parameter.

- *

Compatible Deployments: Cohere Platform

- */ _FinalStage maxInputTokens(Optional maxInputTokens); _FinalStage maxInputTokens(Integer maxInputTokens); - /** - *

Ensures only the top k most likely tokens are considered for generation at each step. - * Defaults to 0, min value of 0, max value of 500.

- *

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

- */ _FinalStage k(Optional k); _FinalStage k(Integer k); - /** - *

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.

- *

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

- */ _FinalStage p(Optional p); _FinalStage p(Double p); - /** - *

If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed.

- *

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

- */ _FinalStage seed(Optional seed); _FinalStage seed(Integer seed); - /** - *

A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.

- *

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

- */ _FinalStage stopSequences(Optional> stopSequences); _FinalStage stopSequences(List stopSequences); - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

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.

- *

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

- */ _FinalStage frequencyPenalty(Optional frequencyPenalty); _FinalStage frequencyPenalty(Double frequencyPenalty); - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

- *

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

- */ _FinalStage presencePenalty(Optional presencePenalty); _FinalStage presencePenalty(Double presencePenalty); - /** - *

A list of available tools (functions) that the model may suggest invoking before producing a text response.

- *

When tools is passed (without tool_results), the text field in the response will be "" and the tool_calls field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the tool_calls array will be empty.

- *

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

- */ + _FinalStage rawPrompting(Optional rawPrompting); + + _FinalStage rawPrompting(Boolean rawPrompting); + + _FinalStage returnPrompt(Optional returnPrompt); + + _FinalStage returnPrompt(Boolean returnPrompt); + _FinalStage tools(Optional> tools); _FinalStage tools(List tools); - /** - *

A list of results from invoking tools recommended by the model in the previous chat turn. Results are used to produce a text response and will be referenced in citations. When using tool_results, tools must be passed as well. - * Each tool_result contains information about how it was invoked, as well as a list of outputs in the form of dictionaries.

- *

Note: outputs must be a list of objects. If your tool returns a single object (eg {"status": 200}), make sure to wrap it in a list.

- *
tool_results = [
-         *   {
-         *     "call": {
-         *       "name": <tool name>,
-         *       "parameters": {
-         *         <param name>: <param value>
-         *       }
-         *     },
-         *     "outputs": [{
-         *       <key>: <value>
-         *     }]
-         *   },
-         *   ...
-         * ]
-         * 
- *

Note: Chat calls with tool_results should not be included in the Chat history to avoid duplication of the message text.

- *

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

- */ _FinalStage toolResults(Optional> toolResults); _FinalStage toolResults(List toolResults); - /** - *

Forces the chat to be single step. Defaults to false.

- */ _FinalStage forceSingleStep(Optional forceSingleStep); _FinalStage forceSingleStep(Boolean forceSingleStep); @@ -750,14 +643,6 @@ public interface _FinalStage { _FinalStage responseFormat(ResponseFormat responseFormat); - /** - *

Used to select the safety instruction inserted into the prompt. Defaults to CONTEXTUAL. - * When NONE is specified, the safety instruction will be omitted.

- *

Safety modes are not yet configurable in combination with tools, tool_results and documents parameters.

- *

Note: This parameter is only compatible newer Cohere models, starting with Command R 08-2024 and Command R+ 08-2024.

- *

Note: command-r7b-12-2024 and newer models only support "CONTEXTUAL" and "STRICT" modes.

- *

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

- */ _FinalStage safetyMode(Optional safetyMode); _FinalStage safetyMode(ChatStreamRequestSafetyMode safetyMode); @@ -777,6 +662,10 @@ public static final class Builder implements MessageStage, _FinalStage { private Optional> tools = Optional.empty(); + private Optional returnPrompt = Optional.empty(); + + private Optional rawPrompting = Optional.empty(); + private Optional presencePenalty = Optional.empty(); private Optional frequencyPenalty = Optional.empty(); @@ -842,6 +731,8 @@ public Builder from(ChatStreamRequest other) { stopSequences(other.getStopSequences()); frequencyPenalty(other.getFrequencyPenalty()); presencePenalty(other.getPresencePenalty()); + rawPrompting(other.getRawPrompting()); + returnPrompt(other.getReturnPrompt()); tools(other.getTools()); toolResults(other.getToolResults()); forceSingleStep(other.getForceSingleStep()); @@ -851,8 +742,6 @@ public Builder from(ChatStreamRequest other) { } /** - *

Text input for the model to respond to.

- *

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

*

Text input for the model to respond to.

*

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

* @return Reference to {@code this} so that method calls can be chained together. @@ -879,14 +768,6 @@ public _FinalStage safetyMode(ChatStreamRequestSafetyMode safetyMode) { return this; } - /** - *

Used to select the safety instruction inserted into the prompt. Defaults to CONTEXTUAL. - * When NONE is specified, the safety instruction will be omitted.

- *

Safety modes are not yet configurable in combination with tools, tool_results and documents parameters.

- *

Note: This parameter is only compatible newer Cohere models, starting with Command R 08-2024 and Command R+ 08-2024.

- *

Note: command-r7b-12-2024 and newer models only support "CONTEXTUAL" and "STRICT" modes.

- *

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

- */ @java.lang.Override @JsonSetter(value = "safety_mode", nulls = Nulls.SKIP) public _FinalStage safetyMode(Optional safetyMode) { @@ -917,9 +798,6 @@ public _FinalStage forceSingleStep(Boolean forceSingleStep) { return this; } - /** - *

Forces the chat to be single step. Defaults to false.

- */ @java.lang.Override @JsonSetter(value = "force_single_step", nulls = Nulls.SKIP) public _FinalStage forceSingleStep(Optional forceSingleStep) { @@ -956,28 +834,6 @@ public _FinalStage toolResults(List toolResults) { return this; } - /** - *

A list of results from invoking tools recommended by the model in the previous chat turn. Results are used to produce a text response and will be referenced in citations. When using tool_results, tools must be passed as well. - * Each tool_result contains information about how it was invoked, as well as a list of outputs in the form of dictionaries.

- *

Note: outputs must be a list of objects. If your tool returns a single object (eg {"status": 200}), make sure to wrap it in a list.

- *
tool_results = [
-         *   {
-         *     "call": {
-         *       "name": <tool name>,
-         *       "parameters": {
-         *         <param name>: <param value>
-         *       }
-         *     },
-         *     "outputs": [{
-         *       <key>: <value>
-         *     }]
-         *   },
-         *   ...
-         * ]
-         * 
- *

Note: Chat calls with tool_results should not be included in the Chat history to avoid duplication of the message text.

- *

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

- */ @java.lang.Override @JsonSetter(value = "tool_results", nulls = Nulls.SKIP) public _FinalStage toolResults(Optional> toolResults) { @@ -997,11 +853,6 @@ public _FinalStage tools(List tools) { return this; } - /** - *

A list of available tools (functions) that the model may suggest invoking before producing a text response.

- *

When tools is passed (without tool_results), the text field in the response will be "" and the tool_calls field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the tool_calls array will be empty.

- *

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

- */ @java.lang.Override @JsonSetter(value = "tools", nulls = Nulls.SKIP) public _FinalStage tools(Optional> tools) { @@ -1010,14 +861,38 @@ public _FinalStage tools(Optional> tools) { } /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

+ *

The prompt is returned in the prompt response field when this is enabled.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage returnPrompt(Boolean returnPrompt) { + this.returnPrompt = Optional.ofNullable(returnPrompt); + return this; + } + + @java.lang.Override + @JsonSetter(value = "return_prompt", nulls = Nulls.SKIP) + public _FinalStage returnPrompt(Optional returnPrompt) { + this.returnPrompt = returnPrompt; + return this; + } + + /** + *

When enabled, the user's prompt will be sent to the model without + * any pre-processing.

*

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

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage presencePenalty(Double presencePenalty) { - this.presencePenalty = Optional.ofNullable(presencePenalty); + public _FinalStage rawPrompting(Boolean rawPrompting) { + this.rawPrompting = Optional.ofNullable(rawPrompting); + return this; + } + + @java.lang.Override + @JsonSetter(value = "raw_prompting", nulls = Nulls.SKIP) + public _FinalStage rawPrompting(Optional rawPrompting) { + this.rawPrompting = rawPrompting; return this; } @@ -1025,7 +900,14 @@ public _FinalStage presencePenalty(Double presencePenalty) { *

Defaults to 0.0, min value of 0.0, max value of 1.0.

*

Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

*

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

+ * @return Reference to {@code this} so that method calls can be chained together. */ + @java.lang.Override + public _FinalStage presencePenalty(Double presencePenalty) { + this.presencePenalty = Optional.ofNullable(presencePenalty); + return this; + } + @java.lang.Override @JsonSetter(value = "presence_penalty", nulls = Nulls.SKIP) public _FinalStage presencePenalty(Optional presencePenalty) { @@ -1045,11 +927,6 @@ public _FinalStage frequencyPenalty(Double frequencyPenalty) { return this; } - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

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.

- *

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

- */ @java.lang.Override @JsonSetter(value = "frequency_penalty", nulls = Nulls.SKIP) public _FinalStage frequencyPenalty(Optional frequencyPenalty) { @@ -1068,10 +945,6 @@ public _FinalStage stopSequences(List stopSequences) { return this; } - /** - *

A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.

- *

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

- */ @java.lang.Override @JsonSetter(value = "stop_sequences", nulls = Nulls.SKIP) public _FinalStage stopSequences(Optional> stopSequences) { @@ -1093,13 +966,6 @@ public _FinalStage seed(Integer seed) { return this; } - /** - *

If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed.

- *

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

- */ @java.lang.Override @JsonSetter(value = "seed", nulls = Nulls.SKIP) public _FinalStage seed(Optional seed) { @@ -1119,11 +985,6 @@ public _FinalStage p(Double p) { return this; } - /** - *

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.

- *

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

- */ @java.lang.Override @JsonSetter(value = "p", nulls = Nulls.SKIP) public _FinalStage p(Optional p) { @@ -1143,11 +1004,6 @@ public _FinalStage k(Integer k) { return this; } - /** - *

Ensures only the top k most likely tokens are considered for generation at each step. - * Defaults to 0, min value of 0, max value of 500.

- *

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

- */ @java.lang.Override @JsonSetter(value = "k", nulls = Nulls.SKIP) public _FinalStage k(Optional k) { @@ -1167,11 +1023,6 @@ public _FinalStage maxInputTokens(Integer maxInputTokens) { return this; } - /** - *

The maximum number of input tokens to send to the model. If not specified, max_input_tokens is the model's context length limit minus a small buffer.

- *

Input will be truncated according to the prompt_truncation parameter.

- *

Compatible Deployments: Cohere Platform

- */ @java.lang.Override @JsonSetter(value = "max_input_tokens", nulls = Nulls.SKIP) public _FinalStage maxInputTokens(Optional maxInputTokens) { @@ -1190,10 +1041,6 @@ public _FinalStage maxTokens(Integer maxTokens) { return this; } - /** - *

The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.

- *

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

- */ @java.lang.Override @JsonSetter(value = "max_tokens", nulls = Nulls.SKIP) public _FinalStage maxTokens(Optional maxTokens) { @@ -1214,12 +1061,6 @@ public _FinalStage temperature(Float temperature) { return this; } - /** - *

Defaults to 0.3.

- *

A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.

- *

Randomness can be further maximized by increasing the value of the p parameter.

- *

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

- */ @java.lang.Override @JsonSetter(value = "temperature", nulls = Nulls.SKIP) public _FinalStage temperature(Optional temperature) { @@ -1239,11 +1080,6 @@ public _FinalStage citationQuality(ChatStreamRequestCitationQuality citationQual return this; } - /** - *

Defaults to "accurate".

- *

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

- *

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

- */ @java.lang.Override @JsonSetter(value = "citation_quality", nulls = Nulls.SKIP) public _FinalStage citationQuality(Optional citationQuality) { @@ -1273,21 +1109,6 @@ public _FinalStage documents(List> documents) { return this; } - /** - *

A list of relevant documents that the model can cite to generate a more accurate reply. Each document is a string-string dictionary.

- *

Example:

- *
[
-         *   { "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
-         *   { "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica." },
-         * ]
-         * 
- *

Keys and values from each document will be serialized to a string and passed to the model. The resulting generation will include citations that reference some of these documents.

- *

Some suggested keys are "text", "author", and "date". For better generation quality, it is recommended to keep the total word count of the strings in the dictionary to under 300 words.

- *

An id field (string) can be optionally supplied to identify the document in the citations. This field will not be passed to the model.

- *

An _excludes field (array of strings) can be optionally supplied to omit some key-value pairs from being shown to the model. The omitted fields will still show up in the citation object. The "_excludes" field will not be passed to the model.

- *

See 'Document Mode' in the guide for more information.

- *

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

- */ @java.lang.Override @JsonSetter(value = "documents", nulls = Nulls.SKIP) public _FinalStage documents(Optional>> documents) { @@ -1307,11 +1128,6 @@ public _FinalStage searchQueriesOnly(Boolean searchQueriesOnly) { return this; } - /** - *

Defaults to false.

- *

When true, the response will only contain a list of generated search queries, but no search will take place, and no reply from the model to the user's message will be generated.

- *

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

- */ @java.lang.Override @JsonSetter(value = "search_queries_only", nulls = Nulls.SKIP) public _FinalStage searchQueriesOnly(Optional searchQueriesOnly) { @@ -1331,11 +1147,6 @@ public _FinalStage connectors(List connectors) { return this; } - /** - *

Accepts {"id": "web-search"}, and/or the "id" for a custom connector, if you've created one.

- *

When specified, the model's reply will be enriched with information found by querying each of the connectors (RAG).

- *

Compatible Deployments: Cohere Platform

- */ @java.lang.Override @JsonSetter(value = "connectors", nulls = Nulls.SKIP) public _FinalStage connectors(Optional> connectors) { @@ -1362,18 +1173,6 @@ public _FinalStage promptTruncation(ChatStreamRequestPromptTruncation promptTrun return this; } - /** - *

Defaults to AUTO when connectors are specified and OFF in all other cases.

- *

Dictates how the prompt will be constructed.

- *

With prompt_truncation set to "AUTO", some elements from chat_history and documents will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be changed and ranked by relevance.

- *

With prompt_truncation set to "AUTO_PRESERVE_ORDER", some elements from chat_history and documents will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be preserved as they are inputted into the API.

- *

With prompt_truncation set to "OFF", no elements will be dropped. If the sum of the inputs exceeds the model's context length limit, a TooManyTokens error will be returned.

- *

Compatible Deployments:

- *
    - *
  • AUTO: Cohere Platform Only
  • - *
  • AUTO_PRESERVE_ORDER: Azure, AWS Sagemaker/Bedrock, Private Deployments
  • - *
- */ @java.lang.Override @JsonSetter(value = "prompt_truncation", nulls = Nulls.SKIP) public _FinalStage promptTruncation(Optional promptTruncation) { @@ -1393,11 +1192,6 @@ public _FinalStage conversationId(String conversationId) { return this; } - /** - *

An alternative to chat_history.

- *

Providing a conversation_id creates or resumes a persisted conversation with the specified ID. The ID can be any non empty string.

- *

Compatible Deployments: Cohere Platform

- */ @java.lang.Override @JsonSetter(value = "conversation_id", nulls = Nulls.SKIP) public _FinalStage conversationId(Optional conversationId) { @@ -1418,12 +1212,6 @@ public _FinalStage chatHistory(List chatHistory) { return this; } - /** - *

A list of previous messages between the user and the model, giving the model conversational context for responding to the user's message.

- *

Each item represents a single message in the chat history, excluding the current user turn. It has two properties: role and message. The role identifies the sender (CHATBOT, SYSTEM, or USER), while the message contains the text content.

- *

The chat_history parameter should not be used for SYSTEM messages in most cases. Instead, to add a SYSTEM role message at the beginning of a conversation, the preamble parameter should be used.

- *

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

- */ @java.lang.Override @JsonSetter(value = "chat_history", nulls = Nulls.SKIP) public _FinalStage chatHistory(Optional> chatHistory) { @@ -1443,11 +1231,6 @@ public _FinalStage preamble(String preamble) { return this; } - /** - *

When specified, the default Cohere preamble will be replaced with the provided one. Preambles are a part of the prompt used to adjust the model's overall behavior and conversation style, and use the SYSTEM role.

- *

The SYSTEM role is also used for the contents of the optional chat_history= parameter. When used with the chat_history= parameter it adds content throughout a conversation. Conversely, when used with the preamble= parameter it adds content at the start of the conversation only.

- *

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

- */ @java.lang.Override @JsonSetter(value = "preamble", nulls = Nulls.SKIP) public _FinalStage preamble(Optional preamble) { @@ -1466,10 +1249,6 @@ public _FinalStage model(String model) { return this; } - /** - *

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

- *

Compatible Deployments: Cohere Platform, Private Deployments

- */ @java.lang.Override @JsonSetter(value = "model", nulls = Nulls.SKIP) public _FinalStage model(Optional model) { @@ -1487,9 +1266,6 @@ public _FinalStage accepts(String accepts) { return this; } - /** - *

Pass text/event-stream to receive the streamed response as server-sent events. The default is \n delimited events.

- */ @java.lang.Override @JsonSetter(value = "Accepts", nulls = Nulls.SKIP) public _FinalStage accepts(Optional accepts) { @@ -1520,6 +1296,8 @@ public ChatStreamRequest build() { stopSequences, frequencyPenalty, presencePenalty, + rawPrompting, + returnPrompt, tools, toolResults, forceSingleStep, diff --git a/src/main/java/com/cohere/api/requests/ClassifyRequest.java b/src/main/java/com/cohere/api/requests/ClassifyRequest.java index 3dd6207..20f9209 100644 --- a/src/main/java/com/cohere/api/requests/ClassifyRequest.java +++ b/src/main/java/com/cohere/api/requests/ClassifyRequest.java @@ -155,11 +155,6 @@ public Builder from(ClassifyRequest other) { return this; } - /** - *

A list of up to 96 texts to be classified. Each one must be a non-empty string. - * There is, however, no consistent, universal limit to the length a particular input can be. We perform classification on the first x tokens of each input, and x varies depending on which underlying model is powering classification. The maximum token length for each model is listed in the "max tokens" column here. - * Note: by default the truncate parameter is set to END, so tokens exceeding the limit will be automatically dropped. This behavior can be disabled by setting truncate to NONE, which will result in validation errors for longer texts.

- */ @JsonSetter(value = "inputs", nulls = Nulls.SKIP) public Builder inputs(List inputs) { this.inputs.clear(); @@ -177,10 +172,6 @@ public Builder addAllInputs(List inputs) { return this; } - /** - *

An array of examples to provide context to the model. Each example is a text string and its associated label/class. Each unique label requires at least 2 examples associated with it; the maximum number of examples is 2500, and each example has a maximum length of 512 tokens. The values should be structured as {text: "...",label: "..."}. - * Note: Fine-tuned Models trained on classification examples don't require the examples parameter to be passed in explicitly.

- */ @JsonSetter(value = "examples", nulls = Nulls.SKIP) public Builder examples(Optional> examples) { this.examples = examples; @@ -192,9 +183,6 @@ public Builder examples(List examples) { return this; } - /** - *

ID of a Fine-tuned Classify model

- */ @JsonSetter(value = "model", nulls = Nulls.SKIP) public Builder model(Optional model) { this.model = model; @@ -206,9 +194,6 @@ public Builder model(String model) { return this; } - /** - *

The ID of a custom playground preset. You can create presets in the playground. If you use a preset, all other parameters become optional, and any included parameters will override the preset's parameters.

- */ @JsonSetter(value = "preset", nulls = Nulls.SKIP) public Builder preset(Optional preset) { this.preset = preset; @@ -220,11 +205,6 @@ public Builder preset(String preset) { return this; } - /** - *

One of NONE|START|END to specify how the API will handle inputs longer than the maximum token length. - * Passing START will discard the start of the input. END will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. - * If NONE is selected, when the input exceeds the maximum input token length an error will be returned.

- */ @JsonSetter(value = "truncate", nulls = Nulls.SKIP) public Builder truncate(Optional truncate) { this.truncate = truncate; diff --git a/src/main/java/com/cohere/api/requests/DetokenizeRequest.java b/src/main/java/com/cohere/api/requests/DetokenizeRequest.java index a5111d5..df3d795 100644 --- a/src/main/java/com/cohere/api/requests/DetokenizeRequest.java +++ b/src/main/java/com/cohere/api/requests/DetokenizeRequest.java @@ -80,9 +80,6 @@ public static ModelStage builder() { } public interface ModelStage { - /** - *

An optional parameter to provide the model name. This will ensure that the detokenization is done by the tokenizer used by that model.

- */ _FinalStage model(@NotNull String model); Builder from(DetokenizeRequest other); @@ -91,9 +88,6 @@ public interface ModelStage { public interface _FinalStage { DetokenizeRequest build(); - /** - *

The list of tokens to be detokenized.

- */ _FinalStage tokens(List tokens); _FinalStage addTokens(Integer tokens); @@ -120,7 +114,6 @@ public Builder from(DetokenizeRequest other) { } /** - *

An optional parameter to provide the model name. This will ensure that the detokenization is done by the tokenizer used by that model.

*

An optional parameter to provide the model name. This will ensure that the detokenization is done by the tokenizer used by that model.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -151,9 +144,6 @@ public _FinalStage addTokens(Integer tokens) { return this; } - /** - *

The list of tokens to be detokenized.

- */ @java.lang.Override @JsonSetter(value = "tokens", nulls = Nulls.SKIP) public _FinalStage tokens(List tokens) { diff --git a/src/main/java/com/cohere/api/requests/EmbedRequest.java b/src/main/java/com/cohere/api/requests/EmbedRequest.java index 25329ed..01025b2 100644 --- a/src/main/java/com/cohere/api/requests/EmbedRequest.java +++ b/src/main/java/com/cohere/api/requests/EmbedRequest.java @@ -174,9 +174,6 @@ public Builder from(EmbedRequest other) { return this; } - /** - *

An array of strings for the model to embed. Maximum number of texts per call is 96.

- */ @JsonSetter(value = "texts", nulls = Nulls.SKIP) public Builder texts(Optional> texts) { this.texts = texts; @@ -188,11 +185,6 @@ public Builder texts(List texts) { return this; } - /** - *

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

- *

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

- *

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

- */ @JsonSetter(value = "images", nulls = Nulls.SKIP) public Builder images(Optional> images) { this.images = images; @@ -204,9 +196,6 @@ public Builder images(List images) { return this; } - /** - *

ID of one of the available Embedding models.

- */ @JsonSetter(value = "model", nulls = Nulls.SKIP) public Builder model(Optional model) { this.model = model; @@ -229,16 +218,6 @@ public Builder inputType(EmbedInputType inputType) { return this; } - /** - *

Specifies the types of embeddings you want to get back. Not required and default is None, which returns the Embed Floats response type. Can be one or more of the following types.

- *
    - *
  • "float": Use this when you want to get back the default float embeddings. Supported with all Embed models.
  • - *
  • "int8": Use this when you want to get back signed int8 embeddings. Supported with Embed v3.0 and newer Embed models.
  • - *
  • "uint8": Use this when you want to get back unsigned int8 embeddings. Supported with Embed v3.0 and newer Embed models.
  • - *
  • "binary": Use this when you want to get back signed binary embeddings. Supported with Embed v3.0 and newer Embed models.
  • - *
  • "ubinary": Use this when you want to get back unsigned binary embeddings. Supported with Embed v3.0 and newer Embed models.
  • - *
- */ @JsonSetter(value = "embedding_types", nulls = Nulls.SKIP) public Builder embeddingTypes(Optional> embeddingTypes) { this.embeddingTypes = embeddingTypes; @@ -250,11 +229,6 @@ public Builder embeddingTypes(List embeddingTypes) { return this; } - /** - *

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

- *

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

- *

If NONE is selected, when the input exceeds the maximum input token length an error will be returned.

- */ @JsonSetter(value = "truncate", nulls = Nulls.SKIP) public Builder truncate(Optional truncate) { this.truncate = truncate; diff --git a/src/main/java/com/cohere/api/requests/GenerateRequest.java b/src/main/java/com/cohere/api/requests/GenerateRequest.java index 016c610..6f957da 100644 --- a/src/main/java/com/cohere/api/requests/GenerateRequest.java +++ b/src/main/java/com/cohere/api/requests/GenerateRequest.java @@ -318,10 +318,6 @@ public static PromptStage builder() { } public interface PromptStage { - /** - *

The input text that serves as the starting point for generating the response. - * Note: The prompt will be pre-processed and modified before reaching the model.

- */ _FinalStage prompt(@NotNull String prompt); Builder from(GenerateRequest other); @@ -330,125 +326,62 @@ public interface PromptStage { public interface _FinalStage { GenerateRequest build(); - /** - *

The identifier of the model to generate with. Currently available models are command (default), command-nightly (experimental), command-light, and command-light-nightly (experimental). - * Smaller, "light" models are faster, while larger models will perform better. Custom models can also be supplied with their full ID.

- */ _FinalStage model(Optional model); _FinalStage model(String model); - /** - *

The maximum number of generations that will be returned. Defaults to 1, min value of 1, max value of 5.

- */ _FinalStage numGenerations(Optional numGenerations); _FinalStage numGenerations(Integer numGenerations); - /** - *

The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.

- *

This parameter is off by default, and if it's not specified, the model will continue generating until it emits an EOS completion token. See BPE Tokens for more details.

- *

Can only be set to 0 if return_likelihoods is set to ALL to get the likelihood of the prompt.

- */ _FinalStage maxTokens(Optional maxTokens); _FinalStage maxTokens(Integer maxTokens); - /** - *

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

- *

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

- *

If NONE is selected, when the input exceeds the maximum input token length an error will be returned.

- */ _FinalStage truncate(Optional truncate); _FinalStage truncate(GenerateRequestTruncate truncate); - /** - *

A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations. See Temperature for more details. - * Defaults to 0.75, min value of 0.0, max value of 5.0.

- */ _FinalStage temperature(Optional temperature); _FinalStage temperature(Double temperature); - /** - *

If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed. - * Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

- */ _FinalStage seed(Optional seed); _FinalStage seed(Integer seed); - /** - *

Identifier of a custom preset. A preset is a combination of parameters, such as prompt, temperature etc. You can create presets in the playground. - * When a preset is specified, the prompt parameter becomes optional, and any included parameters will override the preset's parameters.

- */ _FinalStage preset(Optional preset); _FinalStage preset(String preset); - /** - *

The generated text will be cut at the beginning of the earliest occurrence of an end sequence. The sequence will be excluded from the text.

- */ _FinalStage endSequences(Optional> endSequences); _FinalStage endSequences(List endSequences); - /** - *

The generated text will be cut at the end of the earliest occurrence of a stop sequence. The sequence will be included the text.

- */ _FinalStage stopSequences(Optional> stopSequences); _FinalStage stopSequences(List stopSequences); - /** - *

Ensures only the top k most likely tokens are considered for generation at each step. - * Defaults to 0, min value of 0, max value of 500.

- */ _FinalStage k(Optional k); _FinalStage k(Integer k); - /** - *

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.

- */ _FinalStage p(Optional p); _FinalStage p(Double p); - /** - *

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.

- *

Using frequency_penalty in combination with presence_penalty is not supported on newer models.

- */ _FinalStage frequencyPenalty(Optional frequencyPenalty); _FinalStage frequencyPenalty(Double frequencyPenalty); - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

Can be used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

- *

Using frequency_penalty in combination with presence_penalty is not supported on newer models.

- */ _FinalStage presencePenalty(Optional presencePenalty); _FinalStage presencePenalty(Double presencePenalty); - /** - *

One of GENERATION|NONE to specify how and if the token likelihoods are returned with the response. Defaults to NONE.

- *

If GENERATION is selected, the token likelihoods will only be provided for generated text.

- *

WARNING: ALL is deprecated, and will be removed in a future release.

- */ _FinalStage returnLikelihoods(Optional returnLikelihoods); _FinalStage returnLikelihoods(GenerateRequestReturnLikelihoods returnLikelihoods); - /** - *

When enabled, the user's prompt will be sent to the model without any pre-processing.

- */ _FinalStage rawPrompting(Optional rawPrompting); _FinalStage rawPrompting(Boolean rawPrompting); @@ -515,8 +448,6 @@ public Builder from(GenerateRequest other) { } /** - *

The input text that serves as the starting point for generating the response. - * Note: The prompt will be pre-processed and modified before reaching the model.

*

The input text that serves as the starting point for generating the response. * Note: The prompt will be pre-processed and modified before reaching the model.

* @return Reference to {@code this} so that method calls can be chained together. @@ -538,9 +469,6 @@ public _FinalStage rawPrompting(Boolean rawPrompting) { return this; } - /** - *

When enabled, the user's prompt will be sent to the model without any pre-processing.

- */ @java.lang.Override @JsonSetter(value = "raw_prompting", nulls = Nulls.SKIP) public _FinalStage rawPrompting(Optional rawPrompting) { @@ -560,11 +488,6 @@ public _FinalStage returnLikelihoods(GenerateRequestReturnLikelihoods returnLike return this; } - /** - *

One of GENERATION|NONE to specify how and if the token likelihoods are returned with the response. Defaults to NONE.

- *

If GENERATION is selected, the token likelihoods will only be provided for generated text.

- *

WARNING: ALL is deprecated, and will be removed in a future release.

- */ @java.lang.Override @JsonSetter(value = "return_likelihoods", nulls = Nulls.SKIP) public _FinalStage returnLikelihoods(Optional returnLikelihoods) { @@ -584,11 +507,6 @@ public _FinalStage presencePenalty(Double presencePenalty) { return this; } - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

Can be used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

- *

Using frequency_penalty in combination with presence_penalty is not supported on newer models.

- */ @java.lang.Override @JsonSetter(value = "presence_penalty", nulls = Nulls.SKIP) public _FinalStage presencePenalty(Optional presencePenalty) { @@ -607,10 +525,6 @@ public _FinalStage frequencyPenalty(Double frequencyPenalty) { return this; } - /** - *

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.

- *

Using frequency_penalty in combination with presence_penalty is not supported on newer models.

- */ @java.lang.Override @JsonSetter(value = "frequency_penalty", nulls = Nulls.SKIP) public _FinalStage frequencyPenalty(Optional frequencyPenalty) { @@ -629,10 +543,6 @@ public _FinalStage p(Double p) { return this; } - /** - *

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.

- */ @java.lang.Override @JsonSetter(value = "p", nulls = Nulls.SKIP) public _FinalStage p(Optional p) { @@ -651,10 +561,6 @@ public _FinalStage k(Integer k) { return this; } - /** - *

Ensures only the top k most likely tokens are considered for generation at each step. - * Defaults to 0, min value of 0, max value of 500.

- */ @java.lang.Override @JsonSetter(value = "k", nulls = Nulls.SKIP) public _FinalStage k(Optional k) { @@ -672,9 +578,6 @@ public _FinalStage stopSequences(List stopSequences) { return this; } - /** - *

The generated text will be cut at the end of the earliest occurrence of a stop sequence. The sequence will be included the text.

- */ @java.lang.Override @JsonSetter(value = "stop_sequences", nulls = Nulls.SKIP) public _FinalStage stopSequences(Optional> stopSequences) { @@ -692,9 +595,6 @@ public _FinalStage endSequences(List endSequences) { return this; } - /** - *

The generated text will be cut at the beginning of the earliest occurrence of an end sequence. The sequence will be excluded from the text.

- */ @java.lang.Override @JsonSetter(value = "end_sequences", nulls = Nulls.SKIP) public _FinalStage endSequences(Optional> endSequences) { @@ -713,10 +613,6 @@ public _FinalStage preset(String preset) { return this; } - /** - *

Identifier of a custom preset. A preset is a combination of parameters, such as prompt, temperature etc. You can create presets in the playground. - * When a preset is specified, the prompt parameter becomes optional, and any included parameters will override the preset's parameters.

- */ @java.lang.Override @JsonSetter(value = "preset", nulls = Nulls.SKIP) public _FinalStage preset(Optional preset) { @@ -738,13 +634,6 @@ public _FinalStage seed(Integer seed) { return this; } - /** - *

If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed. - * Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

- */ @java.lang.Override @JsonSetter(value = "seed", nulls = Nulls.SKIP) public _FinalStage seed(Optional seed) { @@ -763,10 +652,6 @@ public _FinalStage temperature(Double temperature) { return this; } - /** - *

A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations. See Temperature for more details. - * Defaults to 0.75, min value of 0.0, max value of 5.0.

- */ @java.lang.Override @JsonSetter(value = "temperature", nulls = Nulls.SKIP) public _FinalStage temperature(Optional temperature) { @@ -786,11 +671,6 @@ public _FinalStage truncate(GenerateRequestTruncate truncate) { return this; } - /** - *

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

- *

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

- *

If NONE is selected, when the input exceeds the maximum input token length an error will be returned.

- */ @java.lang.Override @JsonSetter(value = "truncate", nulls = Nulls.SKIP) public _FinalStage truncate(Optional truncate) { @@ -810,11 +690,6 @@ public _FinalStage maxTokens(Integer maxTokens) { return this; } - /** - *

The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.

- *

This parameter is off by default, and if it's not specified, the model will continue generating until it emits an EOS completion token. See BPE Tokens for more details.

- *

Can only be set to 0 if return_likelihoods is set to ALL to get the likelihood of the prompt.

- */ @java.lang.Override @JsonSetter(value = "max_tokens", nulls = Nulls.SKIP) public _FinalStage maxTokens(Optional maxTokens) { @@ -832,9 +707,6 @@ public _FinalStage numGenerations(Integer numGenerations) { return this; } - /** - *

The maximum number of generations that will be returned. Defaults to 1, min value of 1, max value of 5.

- */ @java.lang.Override @JsonSetter(value = "num_generations", nulls = Nulls.SKIP) public _FinalStage numGenerations(Optional numGenerations) { @@ -853,10 +725,6 @@ public _FinalStage model(String model) { return this; } - /** - *

The identifier of the model to generate with. Currently available models are command (default), command-nightly (experimental), command-light, and command-light-nightly (experimental). - * Smaller, "light" models are faster, while larger models will perform better. Custom models can also be supplied with their full ID.

- */ @java.lang.Override @JsonSetter(value = "model", nulls = Nulls.SKIP) public _FinalStage model(Optional model) { diff --git a/src/main/java/com/cohere/api/requests/GenerateStreamRequest.java b/src/main/java/com/cohere/api/requests/GenerateStreamRequest.java index 062535b..553f4aa 100644 --- a/src/main/java/com/cohere/api/requests/GenerateStreamRequest.java +++ b/src/main/java/com/cohere/api/requests/GenerateStreamRequest.java @@ -318,10 +318,6 @@ public static PromptStage builder() { } public interface PromptStage { - /** - *

The input text that serves as the starting point for generating the response. - * Note: The prompt will be pre-processed and modified before reaching the model.

- */ _FinalStage prompt(@NotNull String prompt); Builder from(GenerateStreamRequest other); @@ -330,125 +326,62 @@ public interface PromptStage { public interface _FinalStage { GenerateStreamRequest build(); - /** - *

The identifier of the model to generate with. Currently available models are command (default), command-nightly (experimental), command-light, and command-light-nightly (experimental). - * Smaller, "light" models are faster, while larger models will perform better. Custom models can also be supplied with their full ID.

- */ _FinalStage model(Optional model); _FinalStage model(String model); - /** - *

The maximum number of generations that will be returned. Defaults to 1, min value of 1, max value of 5.

- */ _FinalStage numGenerations(Optional numGenerations); _FinalStage numGenerations(Integer numGenerations); - /** - *

The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.

- *

This parameter is off by default, and if it's not specified, the model will continue generating until it emits an EOS completion token. See BPE Tokens for more details.

- *

Can only be set to 0 if return_likelihoods is set to ALL to get the likelihood of the prompt.

- */ _FinalStage maxTokens(Optional maxTokens); _FinalStage maxTokens(Integer maxTokens); - /** - *

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

- *

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

- *

If NONE is selected, when the input exceeds the maximum input token length an error will be returned.

- */ _FinalStage truncate(Optional truncate); _FinalStage truncate(GenerateStreamRequestTruncate truncate); - /** - *

A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations. See Temperature for more details. - * Defaults to 0.75, min value of 0.0, max value of 5.0.

- */ _FinalStage temperature(Optional temperature); _FinalStage temperature(Double temperature); - /** - *

If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed. - * Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

- */ _FinalStage seed(Optional seed); _FinalStage seed(Integer seed); - /** - *

Identifier of a custom preset. A preset is a combination of parameters, such as prompt, temperature etc. You can create presets in the playground. - * When a preset is specified, the prompt parameter becomes optional, and any included parameters will override the preset's parameters.

- */ _FinalStage preset(Optional preset); _FinalStage preset(String preset); - /** - *

The generated text will be cut at the beginning of the earliest occurrence of an end sequence. The sequence will be excluded from the text.

- */ _FinalStage endSequences(Optional> endSequences); _FinalStage endSequences(List endSequences); - /** - *

The generated text will be cut at the end of the earliest occurrence of a stop sequence. The sequence will be included the text.

- */ _FinalStage stopSequences(Optional> stopSequences); _FinalStage stopSequences(List stopSequences); - /** - *

Ensures only the top k most likely tokens are considered for generation at each step. - * Defaults to 0, min value of 0, max value of 500.

- */ _FinalStage k(Optional k); _FinalStage k(Integer k); - /** - *

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.

- */ _FinalStage p(Optional p); _FinalStage p(Double p); - /** - *

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.

- *

Using frequency_penalty in combination with presence_penalty is not supported on newer models.

- */ _FinalStage frequencyPenalty(Optional frequencyPenalty); _FinalStage frequencyPenalty(Double frequencyPenalty); - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

Can be used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

- *

Using frequency_penalty in combination with presence_penalty is not supported on newer models.

- */ _FinalStage presencePenalty(Optional presencePenalty); _FinalStage presencePenalty(Double presencePenalty); - /** - *

One of GENERATION|NONE to specify how and if the token likelihoods are returned with the response. Defaults to NONE.

- *

If GENERATION is selected, the token likelihoods will only be provided for generated text.

- *

WARNING: ALL is deprecated, and will be removed in a future release.

- */ _FinalStage returnLikelihoods(Optional returnLikelihoods); _FinalStage returnLikelihoods(GenerateStreamRequestReturnLikelihoods returnLikelihoods); - /** - *

When enabled, the user's prompt will be sent to the model without any pre-processing.

- */ _FinalStage rawPrompting(Optional rawPrompting); _FinalStage rawPrompting(Boolean rawPrompting); @@ -515,8 +448,6 @@ public Builder from(GenerateStreamRequest other) { } /** - *

The input text that serves as the starting point for generating the response. - * Note: The prompt will be pre-processed and modified before reaching the model.

*

The input text that serves as the starting point for generating the response. * Note: The prompt will be pre-processed and modified before reaching the model.

* @return Reference to {@code this} so that method calls can be chained together. @@ -538,9 +469,6 @@ public _FinalStage rawPrompting(Boolean rawPrompting) { return this; } - /** - *

When enabled, the user's prompt will be sent to the model without any pre-processing.

- */ @java.lang.Override @JsonSetter(value = "raw_prompting", nulls = Nulls.SKIP) public _FinalStage rawPrompting(Optional rawPrompting) { @@ -560,11 +488,6 @@ public _FinalStage returnLikelihoods(GenerateStreamRequestReturnLikelihoods retu return this; } - /** - *

One of GENERATION|NONE to specify how and if the token likelihoods are returned with the response. Defaults to NONE.

- *

If GENERATION is selected, the token likelihoods will only be provided for generated text.

- *

WARNING: ALL is deprecated, and will be removed in a future release.

- */ @java.lang.Override @JsonSetter(value = "return_likelihoods", nulls = Nulls.SKIP) public _FinalStage returnLikelihoods(Optional returnLikelihoods) { @@ -584,11 +507,6 @@ public _FinalStage presencePenalty(Double presencePenalty) { return this; } - /** - *

Defaults to 0.0, min value of 0.0, max value of 1.0.

- *

Can be used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

- *

Using frequency_penalty in combination with presence_penalty is not supported on newer models.

- */ @java.lang.Override @JsonSetter(value = "presence_penalty", nulls = Nulls.SKIP) public _FinalStage presencePenalty(Optional presencePenalty) { @@ -607,10 +525,6 @@ public _FinalStage frequencyPenalty(Double frequencyPenalty) { return this; } - /** - *

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.

- *

Using frequency_penalty in combination with presence_penalty is not supported on newer models.

- */ @java.lang.Override @JsonSetter(value = "frequency_penalty", nulls = Nulls.SKIP) public _FinalStage frequencyPenalty(Optional frequencyPenalty) { @@ -629,10 +543,6 @@ public _FinalStage p(Double p) { return this; } - /** - *

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.

- */ @java.lang.Override @JsonSetter(value = "p", nulls = Nulls.SKIP) public _FinalStage p(Optional p) { @@ -651,10 +561,6 @@ public _FinalStage k(Integer k) { return this; } - /** - *

Ensures only the top k most likely tokens are considered for generation at each step. - * Defaults to 0, min value of 0, max value of 500.

- */ @java.lang.Override @JsonSetter(value = "k", nulls = Nulls.SKIP) public _FinalStage k(Optional k) { @@ -672,9 +578,6 @@ public _FinalStage stopSequences(List stopSequences) { return this; } - /** - *

The generated text will be cut at the end of the earliest occurrence of a stop sequence. The sequence will be included the text.

- */ @java.lang.Override @JsonSetter(value = "stop_sequences", nulls = Nulls.SKIP) public _FinalStage stopSequences(Optional> stopSequences) { @@ -692,9 +595,6 @@ public _FinalStage endSequences(List endSequences) { return this; } - /** - *

The generated text will be cut at the beginning of the earliest occurrence of an end sequence. The sequence will be excluded from the text.

- */ @java.lang.Override @JsonSetter(value = "end_sequences", nulls = Nulls.SKIP) public _FinalStage endSequences(Optional> endSequences) { @@ -713,10 +613,6 @@ public _FinalStage preset(String preset) { return this; } - /** - *

Identifier of a custom preset. A preset is a combination of parameters, such as prompt, temperature etc. You can create presets in the playground. - * When a preset is specified, the prompt parameter becomes optional, and any included parameters will override the preset's parameters.

- */ @java.lang.Override @JsonSetter(value = "preset", nulls = Nulls.SKIP) public _FinalStage preset(Optional preset) { @@ -738,13 +634,6 @@ public _FinalStage seed(Integer seed) { return this; } - /** - *

If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed. - * Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

- */ @java.lang.Override @JsonSetter(value = "seed", nulls = Nulls.SKIP) public _FinalStage seed(Optional seed) { @@ -763,10 +652,6 @@ public _FinalStage temperature(Double temperature) { return this; } - /** - *

A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations. See Temperature for more details. - * Defaults to 0.75, min value of 0.0, max value of 5.0.

- */ @java.lang.Override @JsonSetter(value = "temperature", nulls = Nulls.SKIP) public _FinalStage temperature(Optional temperature) { @@ -786,11 +671,6 @@ public _FinalStage truncate(GenerateStreamRequestTruncate truncate) { return this; } - /** - *

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

- *

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

- *

If NONE is selected, when the input exceeds the maximum input token length an error will be returned.

- */ @java.lang.Override @JsonSetter(value = "truncate", nulls = Nulls.SKIP) public _FinalStage truncate(Optional truncate) { @@ -810,11 +690,6 @@ public _FinalStage maxTokens(Integer maxTokens) { return this; } - /** - *

The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.

- *

This parameter is off by default, and if it's not specified, the model will continue generating until it emits an EOS completion token. See BPE Tokens for more details.

- *

Can only be set to 0 if return_likelihoods is set to ALL to get the likelihood of the prompt.

- */ @java.lang.Override @JsonSetter(value = "max_tokens", nulls = Nulls.SKIP) public _FinalStage maxTokens(Optional maxTokens) { @@ -832,9 +707,6 @@ public _FinalStage numGenerations(Integer numGenerations) { return this; } - /** - *

The maximum number of generations that will be returned. Defaults to 1, min value of 1, max value of 5.

- */ @java.lang.Override @JsonSetter(value = "num_generations", nulls = Nulls.SKIP) public _FinalStage numGenerations(Optional numGenerations) { @@ -853,10 +725,6 @@ public _FinalStage model(String model) { return this; } - /** - *

The identifier of the model to generate with. Currently available models are command (default), command-nightly (experimental), command-light, and command-light-nightly (experimental). - * Smaller, "light" models are faster, while larger models will perform better. Custom models can also be supplied with their full ID.

- */ @java.lang.Override @JsonSetter(value = "model", nulls = Nulls.SKIP) public _FinalStage model(Optional model) { diff --git a/src/main/java/com/cohere/api/requests/RerankRequest.java b/src/main/java/com/cohere/api/requests/RerankRequest.java index 5e4c069..690150f 100644 --- a/src/main/java/com/cohere/api/requests/RerankRequest.java +++ b/src/main/java/com/cohere/api/requests/RerankRequest.java @@ -164,9 +164,6 @@ public static QueryStage builder() { } public interface QueryStage { - /** - *

The search query

- */ _FinalStage query(@NotNull String query); Builder from(RerankRequest other); @@ -175,52 +172,28 @@ public interface QueryStage { public interface _FinalStage { RerankRequest build(); - /** - *

The identifier of the model to use, eg rerank-v3.5.

- */ _FinalStage model(Optional model); _FinalStage model(String model); - /** - *

A list of document objects or strings to rerank. - * If a document is provided the text fields is required and all other fields will be preserved in the response.

- *

The total max chunks (length of documents * max_chunks_per_doc) must be less than 10000.

- *

We recommend a maximum of 1,000 documents for optimal endpoint performance.

- */ _FinalStage documents(List documents); _FinalStage addDocuments(RerankRequestDocumentsItem documents); _FinalStage addAllDocuments(List documents); - /** - *

The number of most relevant documents or indices to return, defaults to the length of the documents

- */ _FinalStage topN(Optional topN); _FinalStage topN(Integer topN); - /** - *

If a JSON object is provided, you can specify which keys you would like to have considered for reranking. The model will rerank based on order of the fields passed in (i.e. rank_fields=['title','author','text'] will rerank using the values in title, author, text sequentially. If the length of title, author, and text exceeds the context length of the model, the chunking will not re-consider earlier fields). If not provided, the model will use the default text field for ranking.

- */ _FinalStage rankFields(Optional> rankFields); _FinalStage rankFields(List rankFields); - /** - *
    - *
  • If false, returns results without the doc text - the api will return a list of {index, relevance score} where index is inferred from the list passed into the request.
  • - *
  • If true, returns results with the doc text passed in - the api will return an ordered list of {index, text, relevance score} where index + text refers to the list passed into the request.
  • - *
- */ _FinalStage returnDocuments(Optional returnDocuments); _FinalStage returnDocuments(Boolean returnDocuments); - /** - *

The maximum number of chunks to produce internally from a document

- */ _FinalStage maxChunksPerDoc(Optional maxChunksPerDoc); _FinalStage maxChunksPerDoc(Integer maxChunksPerDoc); @@ -260,7 +233,6 @@ public Builder from(RerankRequest other) { } /** - *

The search query

*

The search query

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -281,9 +253,6 @@ public _FinalStage maxChunksPerDoc(Integer maxChunksPerDoc) { return this; } - /** - *

The maximum number of chunks to produce internally from a document

- */ @java.lang.Override @JsonSetter(value = "max_chunks_per_doc", nulls = Nulls.SKIP) public _FinalStage maxChunksPerDoc(Optional maxChunksPerDoc) { @@ -304,12 +273,6 @@ public _FinalStage returnDocuments(Boolean returnDocuments) { return this; } - /** - *
    - *
  • If false, returns results without the doc text - the api will return a list of {index, relevance score} where index is inferred from the list passed into the request.
  • - *
  • If true, returns results with the doc text passed in - the api will return an ordered list of {index, text, relevance score} where index + text refers to the list passed into the request.
  • - *
- */ @java.lang.Override @JsonSetter(value = "return_documents", nulls = Nulls.SKIP) public _FinalStage returnDocuments(Optional returnDocuments) { @@ -327,9 +290,6 @@ public _FinalStage rankFields(List rankFields) { return this; } - /** - *

If a JSON object is provided, you can specify which keys you would like to have considered for reranking. The model will rerank based on order of the fields passed in (i.e. rank_fields=['title','author','text'] will rerank using the values in title, author, text sequentially. If the length of title, author, and text exceeds the context length of the model, the chunking will not re-consider earlier fields). If not provided, the model will use the default text field for ranking.

- */ @java.lang.Override @JsonSetter(value = "rank_fields", nulls = Nulls.SKIP) public _FinalStage rankFields(Optional> rankFields) { @@ -347,9 +307,6 @@ public _FinalStage topN(Integer topN) { return this; } - /** - *

The number of most relevant documents or indices to return, defaults to the length of the documents

- */ @java.lang.Override @JsonSetter(value = "top_n", nulls = Nulls.SKIP) public _FinalStage topN(Optional topN) { @@ -383,12 +340,6 @@ public _FinalStage addDocuments(RerankRequestDocumentsItem documents) { return this; } - /** - *

A list of document objects or strings to rerank. - * If a document is provided the text fields is required and all other fields will be preserved in the response.

- *

The total max chunks (length of documents * max_chunks_per_doc) must be less than 10000.

- *

We recommend a maximum of 1,000 documents for optimal endpoint performance.

- */ @java.lang.Override @JsonSetter(value = "documents", nulls = Nulls.SKIP) public _FinalStage documents(List documents) { @@ -407,9 +358,6 @@ public _FinalStage model(String model) { return this; } - /** - *

The identifier of the model to use, eg rerank-v3.5.

- */ @java.lang.Override @JsonSetter(value = "model", nulls = Nulls.SKIP) public _FinalStage model(Optional model) { diff --git a/src/main/java/com/cohere/api/requests/SummarizeRequest.java b/src/main/java/com/cohere/api/requests/SummarizeRequest.java index 4f330f7..48aaf4e 100644 --- a/src/main/java/com/cohere/api/requests/SummarizeRequest.java +++ b/src/main/java/com/cohere/api/requests/SummarizeRequest.java @@ -158,9 +158,6 @@ public static TextStage builder() { } public interface TextStage { - /** - *

The text to generate a summary for. Can be up to 100,000 characters long. Currently the only supported language is English.

- */ _FinalStage text(@NotNull String text); Builder from(SummarizeRequest other); @@ -169,44 +166,26 @@ public interface TextStage { public interface _FinalStage { SummarizeRequest build(); - /** - *

One of short, medium, long, or auto defaults to auto. Indicates the approximate length of the summary. If auto is selected, the best option will be picked based on the input text.

- */ _FinalStage length(Optional length); _FinalStage length(SummarizeRequestLength length); - /** - *

One of paragraph, bullets, or auto, defaults to auto. Indicates the style in which the summary will be delivered - in a free form paragraph or in bullet points. If auto is selected, the best option will be picked based on the input text.

- */ _FinalStage format(Optional format); _FinalStage format(SummarizeRequestFormat format); - /** - *

The identifier of the model to generate the summary with. Currently available models are command (default), command-nightly (experimental), command-light, and command-light-nightly (experimental). Smaller, "light" models are faster, while larger models will perform better.

- */ _FinalStage model(Optional model); _FinalStage model(String model); - /** - *

One of low, medium, high, or auto, defaults to auto. Controls how close to the original text the summary is. high extractiveness summaries will lean towards reusing sentences verbatim, while low extractiveness summaries will tend to paraphrase more. If auto is selected, the best option will be picked based on the input text.

- */ _FinalStage extractiveness(Optional extractiveness); _FinalStage extractiveness(SummarizeRequestExtractiveness extractiveness); - /** - *

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.

- */ _FinalStage temperature(Optional temperature); _FinalStage temperature(Double temperature); - /** - *

A free-form instruction for modifying how the summaries get generated. Should complete the sentence "Generate a summary _". Eg. "focusing on the next steps" or "written by Yoda"

- */ _FinalStage additionalCommand(Optional additionalCommand); _FinalStage additionalCommand(String additionalCommand); @@ -246,7 +225,6 @@ public Builder from(SummarizeRequest other) { } /** - *

The text to generate a summary for. Can be up to 100,000 characters long. Currently the only supported language is English.

*

The text to generate a summary for. Can be up to 100,000 characters long. Currently the only supported language is English.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -267,9 +245,6 @@ public _FinalStage additionalCommand(String additionalCommand) { return this; } - /** - *

A free-form instruction for modifying how the summaries get generated. Should complete the sentence "Generate a summary _". Eg. "focusing on the next steps" or "written by Yoda"

- */ @java.lang.Override @JsonSetter(value = "additional_command", nulls = Nulls.SKIP) public _FinalStage additionalCommand(Optional additionalCommand) { @@ -287,9 +262,6 @@ public _FinalStage temperature(Double temperature) { return this; } - /** - *

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.

- */ @java.lang.Override @JsonSetter(value = "temperature", nulls = Nulls.SKIP) public _FinalStage temperature(Optional temperature) { @@ -307,9 +279,6 @@ public _FinalStage extractiveness(SummarizeRequestExtractiveness extractiveness) return this; } - /** - *

One of low, medium, high, or auto, defaults to auto. Controls how close to the original text the summary is. high extractiveness summaries will lean towards reusing sentences verbatim, while low extractiveness summaries will tend to paraphrase more. If auto is selected, the best option will be picked based on the input text.

- */ @java.lang.Override @JsonSetter(value = "extractiveness", nulls = Nulls.SKIP) public _FinalStage extractiveness(Optional extractiveness) { @@ -327,9 +296,6 @@ public _FinalStage model(String model) { return this; } - /** - *

The identifier of the model to generate the summary with. Currently available models are command (default), command-nightly (experimental), command-light, and command-light-nightly (experimental). Smaller, "light" models are faster, while larger models will perform better.

- */ @java.lang.Override @JsonSetter(value = "model", nulls = Nulls.SKIP) public _FinalStage model(Optional model) { @@ -347,9 +313,6 @@ public _FinalStage format(SummarizeRequestFormat format) { return this; } - /** - *

One of paragraph, bullets, or auto, defaults to auto. Indicates the style in which the summary will be delivered - in a free form paragraph or in bullet points. If auto is selected, the best option will be picked based on the input text.

- */ @java.lang.Override @JsonSetter(value = "format", nulls = Nulls.SKIP) public _FinalStage format(Optional format) { @@ -367,9 +330,6 @@ public _FinalStage length(SummarizeRequestLength length) { return this; } - /** - *

One of short, medium, long, or auto defaults to auto. Indicates the approximate length of the summary. If auto is selected, the best option will be picked based on the input text.

- */ @java.lang.Override @JsonSetter(value = "length", nulls = Nulls.SKIP) public _FinalStage length(Optional length) { diff --git a/src/main/java/com/cohere/api/requests/TokenizeRequest.java b/src/main/java/com/cohere/api/requests/TokenizeRequest.java index e054912..ada90db 100644 --- a/src/main/java/com/cohere/api/requests/TokenizeRequest.java +++ b/src/main/java/com/cohere/api/requests/TokenizeRequest.java @@ -77,18 +77,12 @@ public static TextStage builder() { } public interface TextStage { - /** - *

The string to be tokenized, the minimum text length is 1 character, and the maximum text length is 65536 characters.

- */ ModelStage text(@NotNull String text); Builder from(TokenizeRequest other); } public interface ModelStage { - /** - *

The input will be tokenized by the tokenizer that is used by this model.

- */ _FinalStage model(@NotNull String model); } @@ -115,7 +109,6 @@ public Builder from(TokenizeRequest other) { } /** - *

The string to be tokenized, the minimum text length is 1 character, and the maximum text length is 65536 characters.

*

The string to be tokenized, the minimum text length is 1 character, and the maximum text length is 65536 characters.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -127,7 +120,6 @@ public ModelStage text(@NotNull String text) { } /** - *

The input will be tokenized by the tokenizer that is used by this model.

*

The input will be tokenized by the tokenizer that is used by this model.

* @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/resources/connectors/AsyncConnectorsClient.java b/src/main/java/com/cohere/api/resources/connectors/AsyncConnectorsClient.java deleted file mode 100644 index 320f3f5..0000000 --- a/src/main/java/com/cohere/api/resources/connectors/AsyncConnectorsClient.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.connectors; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.resources.connectors.requests.ConnectorsListRequest; -import com.cohere.api.resources.connectors.requests.ConnectorsOAuthAuthorizeRequest; -import com.cohere.api.resources.connectors.requests.CreateConnectorRequest; -import com.cohere.api.resources.connectors.requests.UpdateConnectorRequest; -import com.cohere.api.types.CreateConnectorResponse; -import com.cohere.api.types.GetConnectorResponse; -import com.cohere.api.types.ListConnectorsResponse; -import com.cohere.api.types.OAuthAuthorizeResponse; -import com.cohere.api.types.UpdateConnectorResponse; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -public class AsyncConnectorsClient { - protected final ClientOptions clientOptions; - - private final AsyncRawConnectorsClient rawClient; - - public AsyncConnectorsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawConnectorsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawConnectorsClient withRawResponse() { - return this.rawClient; - } - - /** - * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. - */ - public CompletableFuture list() { - return this.rawClient.list().thenApply(response -> response.body()); - } - - /** - * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. - */ - public CompletableFuture list(ConnectorsListRequest request) { - return this.rawClient.list(request).thenApply(response -> response.body()); - } - - /** - * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. - */ - public CompletableFuture list( - ConnectorsListRequest request, RequestOptions requestOptions) { - return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See 'Creating and Deploying a Connector' for more information. - */ - public CompletableFuture create(CreateConnectorRequest request) { - return this.rawClient.create(request).thenApply(response -> response.body()); - } - - /** - * Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See 'Creating and Deploying a Connector' for more information. - */ - public CompletableFuture create( - CreateConnectorRequest request, RequestOptions requestOptions) { - return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Retrieve a connector by ID. See 'Connectors' for more information. - */ - public CompletableFuture get(String id) { - return this.rawClient.get(id).thenApply(response -> response.body()); - } - - /** - * Retrieve a connector by ID. See 'Connectors' for more information. - */ - public CompletableFuture get(String id, RequestOptions requestOptions) { - return this.rawClient.get(id, requestOptions).thenApply(response -> response.body()); - } - - /** - * Delete a connector by ID. See 'Connectors' for more information. - */ - public CompletableFuture> delete(String id) { - return this.rawClient.delete(id).thenApply(response -> response.body()); - } - - /** - * Delete a connector by ID. See 'Connectors' for more information. - */ - public CompletableFuture> delete(String id, RequestOptions requestOptions) { - return this.rawClient.delete(id, requestOptions).thenApply(response -> response.body()); - } - - /** - * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. - */ - public CompletableFuture update(String id) { - return this.rawClient.update(id).thenApply(response -> response.body()); - } - - /** - * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. - */ - public CompletableFuture update(String id, UpdateConnectorRequest request) { - return this.rawClient.update(id, request).thenApply(response -> response.body()); - } - - /** - * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. - */ - public CompletableFuture update( - String id, UpdateConnectorRequest request, RequestOptions requestOptions) { - return this.rawClient.update(id, request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. - */ - public CompletableFuture oAuthAuthorize(String id) { - return this.rawClient.oAuthAuthorize(id).thenApply(response -> response.body()); - } - - /** - * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. - */ - public CompletableFuture oAuthAuthorize( - String id, ConnectorsOAuthAuthorizeRequest request) { - return this.rawClient.oAuthAuthorize(id, request).thenApply(response -> response.body()); - } - - /** - * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. - */ - public CompletableFuture oAuthAuthorize( - String id, ConnectorsOAuthAuthorizeRequest request, RequestOptions requestOptions) { - return this.rawClient.oAuthAuthorize(id, request, requestOptions).thenApply(response -> response.body()); - } -} diff --git a/src/main/java/com/cohere/api/resources/connectors/AsyncRawConnectorsClient.java b/src/main/java/com/cohere/api/resources/connectors/AsyncRawConnectorsClient.java deleted file mode 100644 index e634341..0000000 --- a/src/main/java/com/cohere/api/resources/connectors/AsyncRawConnectorsClient.java +++ /dev/null @@ -1,855 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.connectors; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.QueryStringMapper; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.connectors.requests.ConnectorsListRequest; -import com.cohere.api.resources.connectors.requests.ConnectorsOAuthAuthorizeRequest; -import com.cohere.api.resources.connectors.requests.CreateConnectorRequest; -import com.cohere.api.resources.connectors.requests.UpdateConnectorRequest; -import com.cohere.api.types.CreateConnectorResponse; -import com.cohere.api.types.GetConnectorResponse; -import com.cohere.api.types.ListConnectorsResponse; -import com.cohere.api.types.OAuthAuthorizeResponse; -import com.cohere.api.types.UpdateConnectorResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; - -public class AsyncRawConnectorsClient { - protected final ClientOptions clientOptions; - - public AsyncRawConnectorsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. - */ - public CompletableFuture> list() { - return list(ConnectorsListRequest.builder().build()); - } - - /** - * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. - */ - public CompletableFuture> list(ConnectorsListRequest request) { - return list(request, null); - } - - /** - * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. - */ - public CompletableFuture> list( - ConnectorsListRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors"); - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "limit", request.getLimit().get(), false); - } - if (request.getOffset().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "offset", request.getOffset().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ListConnectorsResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See 'Creating and Deploying a Connector' for more information. - */ - public CompletableFuture> create(CreateConnectorRequest request) { - return create(request, null); - } - - /** - * Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See 'Creating and Deploying a Connector' for more information. - */ - public CompletableFuture> create( - CreateConnectorRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), CreateConnectorResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Retrieve a connector by ID. See 'Connectors' for more information. - */ - public CompletableFuture> get(String id) { - return get(id, null); - } - - /** - * Retrieve a connector by ID. See 'Connectors' for more information. - */ - public CompletableFuture> get(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetConnectorResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Delete a connector by ID. See 'Connectors' for more information. - */ - public CompletableFuture>> delete(String id) { - return delete(id, null); - } - - /** - * Delete a connector by ID. See 'Connectors' for more information. - */ - public CompletableFuture>> delete(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture>> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. - */ - public CompletableFuture> update(String id) { - return update(id, UpdateConnectorRequest.builder().build()); - } - - /** - * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. - */ - public CompletableFuture> update( - String id, UpdateConnectorRequest request) { - return update(id, request, null); - } - - /** - * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. - */ - public CompletableFuture> update( - String id, UpdateConnectorRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .addPathSegment(id) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PATCH", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), UpdateConnectorResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. - */ - public CompletableFuture> oAuthAuthorize(String id) { - return oAuthAuthorize(id, ConnectorsOAuthAuthorizeRequest.builder().build()); - } - - /** - * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. - */ - public CompletableFuture> oAuthAuthorize( - String id, ConnectorsOAuthAuthorizeRequest request) { - return oAuthAuthorize(id, request, null); - } - - /** - * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. - */ - public CompletableFuture> oAuthAuthorize( - String id, ConnectorsOAuthAuthorizeRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .addPathSegment(id) - .addPathSegments("oauth/authorize"); - if (request.getAfterTokenRedirect().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "after_token_redirect", - request.getAfterTokenRedirect().get(), - false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), OAuthAuthorizeResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/src/main/java/com/cohere/api/resources/connectors/ConnectorsClient.java b/src/main/java/com/cohere/api/resources/connectors/ConnectorsClient.java index e79ebca..5f36370 100644 --- a/src/main/java/com/cohere/api/resources/connectors/ConnectorsClient.java +++ b/src/main/java/com/cohere/api/resources/connectors/ConnectorsClient.java @@ -4,7 +4,23 @@ package com.cohere.api.resources.connectors; import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.CohereApiException; +import com.cohere.api.core.CohereException; +import com.cohere.api.core.MediaTypes; +import com.cohere.api.core.ObjectMappers; import com.cohere.api.core.RequestOptions; +import com.cohere.api.errors.BadRequestError; +import com.cohere.api.errors.ClientClosedRequestError; +import com.cohere.api.errors.ForbiddenError; +import com.cohere.api.errors.GatewayTimeoutError; +import com.cohere.api.errors.InternalServerError; +import com.cohere.api.errors.InvalidTokenError; +import com.cohere.api.errors.NotFoundError; +import com.cohere.api.errors.NotImplementedError; +import com.cohere.api.errors.ServiceUnavailableError; +import com.cohere.api.errors.TooManyRequestsError; +import com.cohere.api.errors.UnauthorizedError; +import com.cohere.api.errors.UnprocessableEntityError; import com.cohere.api.resources.connectors.requests.ConnectorsListRequest; import com.cohere.api.resources.connectors.requests.ConnectorsOAuthAuthorizeRequest; import com.cohere.api.resources.connectors.requests.CreateConnectorRequest; @@ -14,121 +30,474 @@ import com.cohere.api.types.ListConnectorsResponse; import com.cohere.api.types.OAuthAuthorizeResponse; import com.cohere.api.types.UpdateConnectorResponse; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import java.io.IOException; import java.util.Map; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class ConnectorsClient { protected final ClientOptions clientOptions; - private final RawConnectorsClient rawClient; - public ConnectorsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; - this.rawClient = new RawConnectorsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawConnectorsClient withRawResponse() { - return this.rawClient; } /** * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. */ public ListConnectorsResponse list() { - return this.rawClient.list().body(); + return list(ConnectorsListRequest.builder().build()); } /** * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. */ public ListConnectorsResponse list(ConnectorsListRequest request) { - return this.rawClient.list(request).body(); + return list(request, null); } /** * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. */ public ListConnectorsResponse list(ConnectorsListRequest request, RequestOptions requestOptions) { - return this.rawClient.list(request, requestOptions).body(); + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/connectors"); + if (request.getLimit().isPresent()) { + httpUrl.addQueryParameter("limit", request.getLimit().get().toString()); + } + if (request.getOffset().isPresent()) { + httpUrl.addQueryParameter("offset", request.getOffset().get().toString()); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListConnectorsResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See 'Creating and Deploying a Connector' for more information. */ public CreateConnectorResponse create(CreateConnectorRequest request) { - return this.rawClient.create(request).body(); + return create(request, null); } /** * Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See 'Creating and Deploying a Connector' for more information. */ public CreateConnectorResponse create(CreateConnectorRequest request, RequestOptions requestOptions) { - return this.rawClient.create(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/connectors") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateConnectorResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Retrieve a connector by ID. See 'Connectors' for more information. */ public GetConnectorResponse get(String id) { - return this.rawClient.get(id).body(); + return get(id, null); } /** * Retrieve a connector by ID. See 'Connectors' for more information. */ public GetConnectorResponse get(String id, RequestOptions requestOptions) { - return this.rawClient.get(id, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/connectors") + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetConnectorResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Delete a connector by ID. See 'Connectors' for more information. */ public Map delete(String id) { - return this.rawClient.delete(id).body(); + return delete(id, null); } /** * Delete a connector by ID. See 'Connectors' for more information. */ public Map delete(String id, RequestOptions requestOptions) { - return this.rawClient.delete(id, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/connectors") + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), new TypeReference>() {}); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. */ public UpdateConnectorResponse update(String id) { - return this.rawClient.update(id).body(); + return update(id, UpdateConnectorRequest.builder().build()); } /** * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. */ public UpdateConnectorResponse update(String id, UpdateConnectorRequest request) { - return this.rawClient.update(id, request).body(); + return update(id, request, null); } /** * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. */ public UpdateConnectorResponse update(String id, UpdateConnectorRequest request, RequestOptions requestOptions) { - return this.rawClient.update(id, request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/connectors") + .addPathSegment(id) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UpdateConnectorResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. */ public OAuthAuthorizeResponse oAuthAuthorize(String id) { - return this.rawClient.oAuthAuthorize(id).body(); + return oAuthAuthorize(id, ConnectorsOAuthAuthorizeRequest.builder().build()); } /** * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. */ public OAuthAuthorizeResponse oAuthAuthorize(String id, ConnectorsOAuthAuthorizeRequest request) { - return this.rawClient.oAuthAuthorize(id, request).body(); + return oAuthAuthorize(id, request, null); } /** @@ -136,6 +505,77 @@ public OAuthAuthorizeResponse oAuthAuthorize(String id, ConnectorsOAuthAuthorize */ public OAuthAuthorizeResponse oAuthAuthorize( String id, ConnectorsOAuthAuthorizeRequest request, RequestOptions requestOptions) { - return this.rawClient.oAuthAuthorize(id, request, requestOptions).body(); + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/connectors") + .addPathSegment(id) + .addPathSegments("oauth/authorize"); + if (request.getAfterTokenRedirect().isPresent()) { + httpUrl.addQueryParameter( + "after_token_redirect", request.getAfterTokenRedirect().get()); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), OAuthAuthorizeResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw 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 deleted file mode 100644 index 2a23506..0000000 --- a/src/main/java/com/cohere/api/resources/connectors/RawConnectorsClient.java +++ /dev/null @@ -1,624 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.connectors; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.QueryStringMapper; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.connectors.requests.ConnectorsListRequest; -import com.cohere.api.resources.connectors.requests.ConnectorsOAuthAuthorizeRequest; -import com.cohere.api.resources.connectors.requests.CreateConnectorRequest; -import com.cohere.api.resources.connectors.requests.UpdateConnectorRequest; -import com.cohere.api.types.CreateConnectorResponse; -import com.cohere.api.types.GetConnectorResponse; -import com.cohere.api.types.ListConnectorsResponse; -import com.cohere.api.types.OAuthAuthorizeResponse; -import com.cohere.api.types.UpdateConnectorResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import java.io.IOException; -import java.util.Map; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; - -public class RawConnectorsClient { - protected final ClientOptions clientOptions; - - public RawConnectorsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. - */ - public CohereHttpResponse list() { - return list(ConnectorsListRequest.builder().build()); - } - - /** - * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. - */ - public CohereHttpResponse list(ConnectorsListRequest request) { - return list(request, null); - } - - /** - * Returns a list of connectors ordered by descending creation date (newer first). See 'Managing your Connector' for more information. - */ - public CohereHttpResponse list( - ConnectorsListRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors"); - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "limit", request.getLimit().get(), false); - } - if (request.getOffset().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "offset", request.getOffset().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListConnectorsResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See 'Creating and Deploying a Connector' for more information. - */ - public CohereHttpResponse create(CreateConnectorRequest request) { - return create(request, null); - } - - /** - * Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See 'Creating and Deploying a Connector' for more information. - */ - public CohereHttpResponse create( - CreateConnectorRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateConnectorResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Retrieve a connector by ID. See 'Connectors' for more information. - */ - public CohereHttpResponse get(String id) { - return get(id, null); - } - - /** - * Retrieve a connector by ID. See 'Connectors' for more information. - */ - public CohereHttpResponse get(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetConnectorResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Delete a connector by ID. See 'Connectors' for more information. - */ - public CohereHttpResponse> delete(String id) { - return delete(id, null); - } - - /** - * Delete a connector by ID. See 'Connectors' for more information. - */ - public CohereHttpResponse> delete(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. - */ - public CohereHttpResponse update(String id) { - return update(id, UpdateConnectorRequest.builder().build()); - } - - /** - * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. - */ - public CohereHttpResponse update(String id, UpdateConnectorRequest request) { - return update(id, request, null); - } - - /** - * Update a connector by ID. Omitted fields will not be updated. See 'Managing your Connector' for more information. - */ - public CohereHttpResponse update( - String id, UpdateConnectorRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .addPathSegment(id) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PATCH", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UpdateConnectorResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. - */ - public CohereHttpResponse oAuthAuthorize(String id) { - return oAuthAuthorize(id, ConnectorsOAuthAuthorizeRequest.builder().build()); - } - - /** - * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. - */ - public CohereHttpResponse oAuthAuthorize( - String id, ConnectorsOAuthAuthorizeRequest request) { - return oAuthAuthorize(id, request, null); - } - - /** - * Authorize the connector with the given ID for the connector oauth app. See 'Connector Authentication' for more information. - */ - public CohereHttpResponse oAuthAuthorize( - String id, ConnectorsOAuthAuthorizeRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/connectors") - .addPathSegment(id) - .addPathSegments("oauth/authorize"); - if (request.getAfterTokenRedirect().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "after_token_redirect", - request.getAfterTokenRedirect().get(), - false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), OAuthAuthorizeResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } -} diff --git a/src/main/java/com/cohere/api/resources/connectors/requests/ConnectorsListRequest.java b/src/main/java/com/cohere/api/resources/connectors/requests/ConnectorsListRequest.java index 164b84b..0fd69cb 100644 --- a/src/main/java/com/cohere/api/resources/connectors/requests/ConnectorsListRequest.java +++ b/src/main/java/com/cohere/api/resources/connectors/requests/ConnectorsListRequest.java @@ -95,9 +95,6 @@ public Builder from(ConnectorsListRequest other) { return this; } - /** - *

Maximum number of connectors to return [0, 100].

- */ @JsonSetter(value = "limit", nulls = Nulls.SKIP) public Builder limit(Optional limit) { this.limit = limit; @@ -109,9 +106,6 @@ public Builder limit(Double limit) { return this; } - /** - *

Number of connectors to skip before returning results [0, inf].

- */ @JsonSetter(value = "offset", nulls = Nulls.SKIP) public Builder offset(Optional offset) { this.offset = offset; diff --git a/src/main/java/com/cohere/api/resources/connectors/requests/ConnectorsOAuthAuthorizeRequest.java b/src/main/java/com/cohere/api/resources/connectors/requests/ConnectorsOAuthAuthorizeRequest.java index b60b0ae..bb5243b 100644 --- a/src/main/java/com/cohere/api/resources/connectors/requests/ConnectorsOAuthAuthorizeRequest.java +++ b/src/main/java/com/cohere/api/resources/connectors/requests/ConnectorsOAuthAuthorizeRequest.java @@ -81,9 +81,6 @@ public Builder from(ConnectorsOAuthAuthorizeRequest other) { return this; } - /** - *

The URL to redirect to after the connector has been authorized.

- */ @JsonSetter(value = "after_token_redirect", nulls = Nulls.SKIP) public Builder afterTokenRedirect(Optional afterTokenRedirect) { this.afterTokenRedirect = afterTokenRedirect; diff --git a/src/main/java/com/cohere/api/resources/connectors/requests/CreateConnectorRequest.java b/src/main/java/com/cohere/api/resources/connectors/requests/CreateConnectorRequest.java index 04683f4..6c77041 100644 --- a/src/main/java/com/cohere/api/resources/connectors/requests/CreateConnectorRequest.java +++ b/src/main/java/com/cohere/api/resources/connectors/requests/CreateConnectorRequest.java @@ -172,62 +172,38 @@ public static NameStage builder() { } public interface NameStage { - /** - *

A human-readable name for the connector.

- */ UrlStage name(@NotNull String name); Builder from(CreateConnectorRequest other); } public interface UrlStage { - /** - *

The URL of the connector that will be used to search for documents.

- */ _FinalStage url(@NotNull String url); } public interface _FinalStage { CreateConnectorRequest build(); - /** - *

A description of the connector.

- */ _FinalStage description(Optional description); _FinalStage description(String description); - /** - *

A list of fields to exclude from the prompt (fields remain in the document).

- */ _FinalStage excludes(Optional> excludes); _FinalStage excludes(List excludes); - /** - *

The OAuth 2.0 configuration for the connector. Cannot be specified if service_auth is specified.

- */ _FinalStage oauth(Optional oauth); _FinalStage oauth(CreateConnectorOAuth oauth); - /** - *

Whether the connector is active or not.

- */ _FinalStage active(Optional active); _FinalStage active(Boolean active); - /** - *

Whether a chat request should continue or not if the request to this connector fails.

- */ _FinalStage continueOnFailure(Optional continueOnFailure); _FinalStage continueOnFailure(Boolean continueOnFailure); - /** - *

The service to service authentication configuration for the connector. Cannot be specified if oauth is specified.

- */ _FinalStage serviceAuth(Optional serviceAuth); _FinalStage serviceAuth(CreateConnectorServiceAuth serviceAuth); @@ -270,7 +246,6 @@ public Builder from(CreateConnectorRequest other) { } /** - *

A human-readable name for the connector.

*

A human-readable name for the connector.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -282,7 +257,6 @@ public UrlStage name(@NotNull String name) { } /** - *

The URL of the connector that will be used to search for documents.

*

The URL of the connector that will be used to search for documents.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -303,9 +277,6 @@ public _FinalStage serviceAuth(CreateConnectorServiceAuth serviceAuth) { return this; } - /** - *

The service to service authentication configuration for the connector. Cannot be specified if oauth is specified.

- */ @java.lang.Override @JsonSetter(value = "service_auth", nulls = Nulls.SKIP) public _FinalStage serviceAuth(Optional serviceAuth) { @@ -323,9 +294,6 @@ public _FinalStage continueOnFailure(Boolean continueOnFailure) { return this; } - /** - *

Whether a chat request should continue or not if the request to this connector fails.

- */ @java.lang.Override @JsonSetter(value = "continue_on_failure", nulls = Nulls.SKIP) public _FinalStage continueOnFailure(Optional continueOnFailure) { @@ -343,9 +311,6 @@ public _FinalStage active(Boolean active) { return this; } - /** - *

Whether the connector is active or not.

- */ @java.lang.Override @JsonSetter(value = "active", nulls = Nulls.SKIP) public _FinalStage active(Optional active) { @@ -363,9 +328,6 @@ public _FinalStage oauth(CreateConnectorOAuth oauth) { return this; } - /** - *

The OAuth 2.0 configuration for the connector. Cannot be specified if service_auth is specified.

- */ @java.lang.Override @JsonSetter(value = "oauth", nulls = Nulls.SKIP) public _FinalStage oauth(Optional oauth) { @@ -383,9 +345,6 @@ public _FinalStage excludes(List excludes) { return this; } - /** - *

A list of fields to exclude from the prompt (fields remain in the document).

- */ @java.lang.Override @JsonSetter(value = "excludes", nulls = Nulls.SKIP) public _FinalStage excludes(Optional> excludes) { @@ -403,9 +362,6 @@ public _FinalStage description(String description) { return this; } - /** - *

A description of the connector.

- */ @java.lang.Override @JsonSetter(value = "description", nulls = Nulls.SKIP) public _FinalStage description(Optional description) { diff --git a/src/main/java/com/cohere/api/resources/connectors/requests/UpdateConnectorRequest.java b/src/main/java/com/cohere/api/resources/connectors/requests/UpdateConnectorRequest.java index 0f4eae7..6ca401c 100644 --- a/src/main/java/com/cohere/api/resources/connectors/requests/UpdateConnectorRequest.java +++ b/src/main/java/com/cohere/api/resources/connectors/requests/UpdateConnectorRequest.java @@ -176,9 +176,6 @@ public Builder from(UpdateConnectorRequest other) { return this; } - /** - *

A human-readable name for the connector.

- */ @JsonSetter(value = "name", nulls = Nulls.SKIP) public Builder name(Optional name) { this.name = name; @@ -190,9 +187,6 @@ public Builder name(String name) { return this; } - /** - *

The URL of the connector that will be used to search for documents.

- */ @JsonSetter(value = "url", nulls = Nulls.SKIP) public Builder url(Optional url) { this.url = url; @@ -204,9 +198,6 @@ public Builder url(String url) { return this; } - /** - *

A list of fields to exclude from the prompt (fields remain in the document).

- */ @JsonSetter(value = "excludes", nulls = Nulls.SKIP) public Builder excludes(Optional> excludes) { this.excludes = excludes; @@ -218,9 +209,6 @@ public Builder excludes(List excludes) { return this; } - /** - *

The OAuth 2.0 configuration for the connector. Cannot be specified if service_auth is specified.

- */ @JsonSetter(value = "oauth", nulls = Nulls.SKIP) public Builder oauth(Optional oauth) { this.oauth = oauth; @@ -254,9 +242,6 @@ public Builder continueOnFailure(Boolean continueOnFailure) { return this; } - /** - *

The service to service authentication configuration for the connector. Cannot be specified if oauth is specified.

- */ @JsonSetter(value = "service_auth", nulls = Nulls.SKIP) public Builder serviceAuth(Optional serviceAuth) { this.serviceAuth = serviceAuth; diff --git a/src/main/java/com/cohere/api/resources/datasets/AsyncDatasetsClient.java b/src/main/java/com/cohere/api/resources/datasets/AsyncDatasetsClient.java deleted file mode 100644 index 3f99786..0000000 --- a/src/main/java/com/cohere/api/resources/datasets/AsyncDatasetsClient.java +++ /dev/null @@ -1,114 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.datasets; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.resources.datasets.requests.DatasetsCreateRequest; -import com.cohere.api.resources.datasets.requests.DatasetsListRequest; -import com.cohere.api.resources.datasets.types.DatasetsCreateResponse; -import com.cohere.api.resources.datasets.types.DatasetsGetResponse; -import com.cohere.api.resources.datasets.types.DatasetsGetUsageResponse; -import com.cohere.api.resources.datasets.types.DatasetsListResponse; -import java.io.File; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -public class AsyncDatasetsClient { - protected final ClientOptions clientOptions; - - private final AsyncRawDatasetsClient rawClient; - - public AsyncDatasetsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawDatasetsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawDatasetsClient withRawResponse() { - return this.rawClient; - } - - /** - * List datasets that have been created. - */ - public CompletableFuture list() { - return this.rawClient.list().thenApply(response -> response.body()); - } - - /** - * List datasets that have been created. - */ - public CompletableFuture list(DatasetsListRequest request) { - return this.rawClient.list(request).thenApply(response -> response.body()); - } - - /** - * List datasets that have been created. - */ - public CompletableFuture list(DatasetsListRequest request, RequestOptions requestOptions) { - return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Create a dataset by uploading a file. See 'Dataset Creation' for more information. - */ - public CompletableFuture create( - File data, Optional evalData, DatasetsCreateRequest request) { - return this.rawClient.create(data, evalData, request).thenApply(response -> response.body()); - } - - /** - * Create a dataset by uploading a file. See 'Dataset Creation' for more information. - */ - public CompletableFuture create( - File data, Optional evalData, DatasetsCreateRequest request, RequestOptions requestOptions) { - return this.rawClient.create(data, evalData, request, requestOptions).thenApply(response -> response.body()); - } - - /** - * View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users. - */ - public CompletableFuture getUsage() { - return this.rawClient.getUsage().thenApply(response -> response.body()); - } - - /** - * View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users. - */ - public CompletableFuture getUsage(RequestOptions requestOptions) { - return this.rawClient.getUsage(requestOptions).thenApply(response -> response.body()); - } - - /** - * Retrieve a dataset by ID. See 'Datasets' for more information. - */ - public CompletableFuture get(String id) { - return this.rawClient.get(id).thenApply(response -> response.body()); - } - - /** - * Retrieve a dataset by ID. See 'Datasets' for more information. - */ - public CompletableFuture get(String id, RequestOptions requestOptions) { - return this.rawClient.get(id, requestOptions).thenApply(response -> response.body()); - } - - /** - * Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually. - */ - public CompletableFuture> delete(String id) { - return this.rawClient.delete(id).thenApply(response -> response.body()); - } - - /** - * Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually. - */ - public CompletableFuture> delete(String id, RequestOptions requestOptions) { - return this.rawClient.delete(id, requestOptions).thenApply(response -> response.body()); - } -} diff --git a/src/main/java/com/cohere/api/resources/datasets/AsyncRawDatasetsClient.java b/src/main/java/com/cohere/api/resources/datasets/AsyncRawDatasetsClient.java deleted file mode 100644 index 7ad14e7..0000000 --- a/src/main/java/com/cohere/api/resources/datasets/AsyncRawDatasetsClient.java +++ /dev/null @@ -1,751 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.datasets; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.QueryStringMapper; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.datasets.requests.DatasetsCreateRequest; -import com.cohere.api.resources.datasets.requests.DatasetsListRequest; -import com.cohere.api.resources.datasets.types.DatasetsCreateResponse; -import com.cohere.api.resources.datasets.types.DatasetsGetResponse; -import com.cohere.api.resources.datasets.types.DatasetsGetUsageResponse; -import com.cohere.api.resources.datasets.types.DatasetsListResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; - -public class AsyncRawDatasetsClient { - protected final ClientOptions clientOptions; - - public AsyncRawDatasetsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * List datasets that have been created. - */ - public CompletableFuture> list() { - return list(DatasetsListRequest.builder().build()); - } - - /** - * List datasets that have been created. - */ - public CompletableFuture> list(DatasetsListRequest request) { - return list(request, null); - } - - /** - * List datasets that have been created. - */ - public CompletableFuture> list( - DatasetsListRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets"); - if (request.getDatasetType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "datasetType", request.getDatasetType().get(), false); - } - if (request.getBefore().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "before", request.getBefore().get(), false); - } - if (request.getAfter().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "after", request.getAfter().get(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "limit", request.getLimit().get(), false); - } - if (request.getOffset().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "offset", request.getOffset().get(), false); - } - if (request.getValidationStatus().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "validationStatus", request.getValidationStatus().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsListResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Create a dataset by uploading a file. See 'Dataset Creation' for more information. - */ - public CompletableFuture> create( - File data, Optional evalData, DatasetsCreateRequest request) { - return create(data, evalData, request, null); - } - - /** - * Create a dataset by uploading a file. See 'Dataset Creation' for more information. - */ - public CompletableFuture> create( - File data, Optional evalData, DatasetsCreateRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets"); - QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName(), false); - QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType(), false); - if (request.getKeepOriginalFile().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "keep_original_file", request.getKeepOriginalFile().get(), false); - } - if (request.getSkipMalformedInput().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "skip_malformed_input", - request.getSkipMalformedInput().get(), - false); - } - if (request.getTextSeparator().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "text_separator", request.getTextSeparator().get(), false); - } - if (request.getCsvDelimiter().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "csv_delimiter", request.getCsvDelimiter().get(), false); - } - if (request.getKeepFields().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "keep_fields", request.getKeepFields().get(), true); - } - if (request.getOptionalFields().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "optional_fields", request.getOptionalFields().get(), true); - } - MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); - try { - String dataMimeType = Files.probeContentType(data.toPath()); - MediaType dataMimeTypeMediaType = dataMimeType != null ? MediaType.parse(dataMimeType) : null; - body.addFormDataPart("data", data.getName(), RequestBody.create(data, dataMimeTypeMediaType)); - if (evalData.isPresent()) { - String evalDataMimeType = Files.probeContentType(evalData.get().toPath()); - MediaType evalDataMimeTypeMediaType = - evalDataMimeType != null ? MediaType.parse(evalDataMimeType) : null; - body.addFormDataPart( - "eval_data", - evalData.get().getName(), - RequestBody.create(evalData.get(), evalDataMimeTypeMediaType)); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("POST", body.build()) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DatasetsCreateResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users. - */ - public CompletableFuture> getUsage() { - return getUsage(null); - } - - /** - * View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users. - */ - public CompletableFuture> getUsage(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets/usage") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DatasetsGetUsageResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Retrieve a dataset by ID. See 'Datasets' for more information. - */ - public CompletableFuture> get(String id) { - return get(id, null); - } - - /** - * Retrieve a dataset by ID. See 'Datasets' for more information. - */ - public CompletableFuture> get(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsGetResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually. - */ - public CompletableFuture>> delete(String id) { - return delete(id, null); - } - - /** - * Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually. - */ - public CompletableFuture>> delete(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture>> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/src/main/java/com/cohere/api/resources/datasets/DatasetsClient.java b/src/main/java/com/cohere/api/resources/datasets/DatasetsClient.java index 58a5141..75c986a 100644 --- a/src/main/java/com/cohere/api/resources/datasets/DatasetsClient.java +++ b/src/main/java/com/cohere/api/resources/datasets/DatasetsClient.java @@ -4,60 +4,162 @@ package com.cohere.api.resources.datasets; import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.CohereApiException; +import com.cohere.api.core.CohereException; +import com.cohere.api.core.ObjectMappers; import com.cohere.api.core.RequestOptions; +import com.cohere.api.errors.BadRequestError; +import com.cohere.api.errors.ClientClosedRequestError; +import com.cohere.api.errors.ForbiddenError; +import com.cohere.api.errors.GatewayTimeoutError; +import com.cohere.api.errors.InternalServerError; +import com.cohere.api.errors.InvalidTokenError; +import com.cohere.api.errors.NotFoundError; +import com.cohere.api.errors.NotImplementedError; +import com.cohere.api.errors.ServiceUnavailableError; +import com.cohere.api.errors.TooManyRequestsError; +import com.cohere.api.errors.UnauthorizedError; +import com.cohere.api.errors.UnprocessableEntityError; import com.cohere.api.resources.datasets.requests.DatasetsCreateRequest; import com.cohere.api.resources.datasets.requests.DatasetsListRequest; import com.cohere.api.resources.datasets.types.DatasetsCreateResponse; import com.cohere.api.resources.datasets.types.DatasetsGetResponse; import com.cohere.api.resources.datasets.types.DatasetsGetUsageResponse; import com.cohere.api.resources.datasets.types.DatasetsListResponse; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import java.io.File; +import java.io.IOException; +import java.nio.file.Files; import java.util.Map; import java.util.Optional; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class DatasetsClient { protected final ClientOptions clientOptions; - private final RawDatasetsClient rawClient; - public DatasetsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; - this.rawClient = new RawDatasetsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawDatasetsClient withRawResponse() { - return this.rawClient; } /** * List datasets that have been created. */ public DatasetsListResponse list() { - return this.rawClient.list().body(); + return list(DatasetsListRequest.builder().build()); } /** * List datasets that have been created. */ public DatasetsListResponse list(DatasetsListRequest request) { - return this.rawClient.list(request).body(); + return list(request, null); } /** * List datasets that have been created. */ public DatasetsListResponse list(DatasetsListRequest request, RequestOptions requestOptions) { - return this.rawClient.list(request, requestOptions).body(); + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/datasets"); + if (request.getDatasetType().isPresent()) { + httpUrl.addQueryParameter("datasetType", request.getDatasetType().get()); + } + if (request.getBefore().isPresent()) { + httpUrl.addQueryParameter("before", request.getBefore().get().toString()); + } + if (request.getAfter().isPresent()) { + httpUrl.addQueryParameter("after", request.getAfter().get().toString()); + } + if (request.getLimit().isPresent()) { + httpUrl.addQueryParameter("limit", request.getLimit().get().toString()); + } + if (request.getOffset().isPresent()) { + httpUrl.addQueryParameter("offset", request.getOffset().get().toString()); + } + if (request.getValidationStatus().isPresent()) { + httpUrl.addQueryParameter( + "validationStatus", request.getValidationStatus().get().toString()); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsListResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Create a dataset by uploading a file. See 'Dataset Creation' for more information. */ public DatasetsCreateResponse create(File data, Optional evalData, DatasetsCreateRequest request) { - return this.rawClient.create(data, evalData, request).body(); + return create(data, evalData, request, null); } /** @@ -65,48 +167,358 @@ public DatasetsCreateResponse create(File data, Optional evalData, Dataset */ public DatasetsCreateResponse create( File data, Optional evalData, DatasetsCreateRequest request, RequestOptions requestOptions) { - return this.rawClient.create(data, evalData, request, requestOptions).body(); + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/datasets"); + httpUrl.addQueryParameter("name", request.getName()); + httpUrl.addQueryParameter("type", request.getType().toString()); + if (request.getKeepOriginalFile().isPresent()) { + httpUrl.addQueryParameter( + "keep_original_file", request.getKeepOriginalFile().get().toString()); + } + if (request.getSkipMalformedInput().isPresent()) { + httpUrl.addQueryParameter( + "skip_malformed_input", + request.getSkipMalformedInput().get().toString()); + } + if (request.getKeepFields().isPresent()) { + httpUrl.addQueryParameter("keep_fields", request.getKeepFields().get()); + } + if (request.getOptionalFields().isPresent()) { + httpUrl.addQueryParameter( + "optional_fields", request.getOptionalFields().get()); + } + if (request.getTextSeparator().isPresent()) { + httpUrl.addQueryParameter( + "text_separator", request.getTextSeparator().get()); + } + if (request.getCsvDelimiter().isPresent()) { + httpUrl.addQueryParameter("csv_delimiter", request.getCsvDelimiter().get()); + } + if (request.getDryRun().isPresent()) { + httpUrl.addQueryParameter("dry_run", request.getDryRun().get().toString()); + } + MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); + try { + String dataMimeType = Files.probeContentType(data.toPath()); + MediaType dataMimeTypeMediaType = dataMimeType != null ? MediaType.parse(dataMimeType) : null; + body.addFormDataPart("data", data.getName(), RequestBody.create(dataMimeTypeMediaType, data)); + if (evalData.isPresent()) { + String evalDataMimeType = Files.probeContentType(evalData.get().toPath()); + MediaType evalDataMimeTypeMediaType = + evalDataMimeType != null ? MediaType.parse(evalDataMimeType) : null; + body.addFormDataPart( + "eval_data", + evalData.get().getName(), + RequestBody.create(evalDataMimeTypeMediaType, evalData.get())); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("POST", body.build()) + .headers(Headers.of(clientOptions.headers(requestOptions))); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsCreateResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users. */ public DatasetsGetUsageResponse getUsage() { - return this.rawClient.getUsage().body(); + return getUsage(null); } /** * View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users. */ public DatasetsGetUsageResponse getUsage(RequestOptions requestOptions) { - return this.rawClient.getUsage(requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/datasets/usage") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsGetUsageResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Retrieve a dataset by ID. See 'Datasets' for more information. */ public DatasetsGetResponse get(String id) { - return this.rawClient.get(id).body(); + return get(id, null); } /** * Retrieve a dataset by ID. See 'Datasets' for more information. */ public DatasetsGetResponse get(String id, RequestOptions requestOptions) { - return this.rawClient.get(id, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/datasets") + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsGetResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually. */ public Map delete(String id) { - return this.rawClient.delete(id).body(); + return delete(id, null); } /** * Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually. */ public Map delete(String id, RequestOptions requestOptions) { - return this.rawClient.delete(id, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/datasets") + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), new TypeReference>() {}); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw 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 deleted file mode 100644 index 382f180..0000000 --- a/src/main/java/com/cohere/api/resources/datasets/RawDatasetsClient.java +++ /dev/null @@ -1,559 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.datasets; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.QueryStringMapper; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.datasets.requests.DatasetsCreateRequest; -import com.cohere.api.resources.datasets.requests.DatasetsListRequest; -import com.cohere.api.resources.datasets.types.DatasetsCreateResponse; -import com.cohere.api.resources.datasets.types.DatasetsGetResponse; -import com.cohere.api.resources.datasets.types.DatasetsGetUsageResponse; -import com.cohere.api.resources.datasets.types.DatasetsListResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Map; -import java.util.Optional; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; - -public class RawDatasetsClient { - protected final ClientOptions clientOptions; - - public RawDatasetsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * List datasets that have been created. - */ - public CohereHttpResponse list() { - return list(DatasetsListRequest.builder().build()); - } - - /** - * List datasets that have been created. - */ - public CohereHttpResponse list(DatasetsListRequest request) { - return list(request, null); - } - - /** - * List datasets that have been created. - */ - public CohereHttpResponse list(DatasetsListRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets"); - if (request.getDatasetType().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "datasetType", request.getDatasetType().get(), false); - } - if (request.getBefore().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "before", request.getBefore().get(), false); - } - if (request.getAfter().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "after", request.getAfter().get(), false); - } - if (request.getLimit().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "limit", request.getLimit().get(), false); - } - if (request.getOffset().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "offset", request.getOffset().get(), false); - } - if (request.getValidationStatus().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "validationStatus", request.getValidationStatus().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsListResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Create a dataset by uploading a file. See 'Dataset Creation' for more information. - */ - public CohereHttpResponse create( - File data, Optional evalData, DatasetsCreateRequest request) { - return create(data, evalData, request, null); - } - - /** - * Create a dataset by uploading a file. See 'Dataset Creation' for more information. - */ - public CohereHttpResponse create( - File data, Optional evalData, DatasetsCreateRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets"); - QueryStringMapper.addQueryParameter(httpUrl, "name", request.getName(), false); - QueryStringMapper.addQueryParameter(httpUrl, "type", request.getType(), false); - if (request.getKeepOriginalFile().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "keep_original_file", request.getKeepOriginalFile().get(), false); - } - if (request.getSkipMalformedInput().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, - "skip_malformed_input", - request.getSkipMalformedInput().get(), - false); - } - if (request.getTextSeparator().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "text_separator", request.getTextSeparator().get(), false); - } - if (request.getCsvDelimiter().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "csv_delimiter", request.getCsvDelimiter().get(), false); - } - if (request.getKeepFields().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "keep_fields", request.getKeepFields().get(), true); - } - if (request.getOptionalFields().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "optional_fields", request.getOptionalFields().get(), true); - } - MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); - try { - String dataMimeType = Files.probeContentType(data.toPath()); - MediaType dataMimeTypeMediaType = dataMimeType != null ? MediaType.parse(dataMimeType) : null; - body.addFormDataPart("data", data.getName(), RequestBody.create(data, dataMimeTypeMediaType)); - if (evalData.isPresent()) { - String evalDataMimeType = Files.probeContentType(evalData.get().toPath()); - MediaType evalDataMimeTypeMediaType = - evalDataMimeType != null ? MediaType.parse(evalDataMimeType) : null; - body.addFormDataPart( - "eval_data", - evalData.get().getName(), - RequestBody.create(evalData.get(), evalDataMimeTypeMediaType)); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("POST", body.build()) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsCreateResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users. - */ - public CohereHttpResponse getUsage() { - return getUsage(null); - } - - /** - * View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users. - */ - public CohereHttpResponse getUsage(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets/usage") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsGetUsageResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Retrieve a dataset by ID. See 'Datasets' for more information. - */ - public CohereHttpResponse get(String id) { - return get(id, null); - } - - /** - * Retrieve a dataset by ID. See 'Datasets' for more information. - */ - public CohereHttpResponse get(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsGetResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually. - */ - public CohereHttpResponse> delete(String id) { - return delete(id, null); - } - - /** - * Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually. - */ - public CohereHttpResponse> delete(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/datasets") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } -} diff --git a/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsCreateRequest.java b/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsCreateRequest.java index fda96a8..36b688f 100644 --- a/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsCreateRequest.java +++ b/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsCreateRequest.java @@ -13,9 +13,7 @@ import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -24,10 +22,6 @@ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonDeserialize(builder = DatasetsCreateRequest.Builder.class) public final class DatasetsCreateRequest { - private final Optional> keepFields; - - private final Optional> optionalFields; - private final String name; private final DatasetType type; @@ -36,49 +30,41 @@ public final class DatasetsCreateRequest { private final Optional skipMalformedInput; + private final Optional keepFields; + + private final Optional optionalFields; + private final Optional textSeparator; private final Optional csvDelimiter; + private final Optional dryRun; + private final Map additionalProperties; private DatasetsCreateRequest( - Optional> keepFields, - Optional> optionalFields, String name, DatasetType type, Optional keepOriginalFile, Optional skipMalformedInput, + Optional keepFields, + Optional optionalFields, Optional textSeparator, Optional csvDelimiter, + Optional dryRun, Map additionalProperties) { - this.keepFields = keepFields; - this.optionalFields = optionalFields; this.name = name; this.type = type; this.keepOriginalFile = keepOriginalFile; this.skipMalformedInput = skipMalformedInput; + this.keepFields = keepFields; + this.optionalFields = optionalFields; this.textSeparator = textSeparator; this.csvDelimiter = csvDelimiter; + this.dryRun = dryRun; this.additionalProperties = additionalProperties; } - /** - * @return List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, datasets of type embed-input will drop all fields other than the required text field. If any of the fields in keep_fields are missing from the uploaded file, Dataset validation will fail. - */ - @JsonProperty("keep_fields") - public Optional> getKeepFields() { - return keepFields; - } - - /** - * @return List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, Datasets of type embed-input will drop all fields other than the required text field. If any of the fields in optional_fields are missing from the uploaded file, Dataset validation will pass. - */ - @JsonProperty("optional_fields") - public Optional> getOptionalFields() { - return optionalFields; - } - /** * @return The name of the uploaded dataset. */ @@ -111,6 +97,22 @@ public Optional getSkipMalformedInput() { return skipMalformedInput; } + /** + * @return List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, datasets of type embed-input will drop all fields other than the required text field. If any of the fields in keep_fields are missing from the uploaded file, Dataset validation will fail. + */ + @JsonProperty("keep_fields") + public Optional getKeepFields() { + return keepFields; + } + + /** + * @return List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, Datasets of type embed-input will drop all fields other than the required text field. If any of the fields in optional_fields are missing from the uploaded file, Dataset validation will pass. + */ + @JsonProperty("optional_fields") + public Optional getOptionalFields() { + return optionalFields; + } + /** * @return Raw .txt uploads will be split into entries using the text_separator value. */ @@ -127,6 +129,14 @@ public Optional getCsvDelimiter() { return csvDelimiter; } + /** + * @return flag to enable dry_run mode + */ + @JsonProperty("dry_run") + public Optional getDryRun() { + return dryRun; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -139,27 +149,29 @@ public Map getAdditionalProperties() { } private boolean equalTo(DatasetsCreateRequest other) { - return keepFields.equals(other.keepFields) - && optionalFields.equals(other.optionalFields) - && name.equals(other.name) + return name.equals(other.name) && type.equals(other.type) && keepOriginalFile.equals(other.keepOriginalFile) && skipMalformedInput.equals(other.skipMalformedInput) + && keepFields.equals(other.keepFields) + && optionalFields.equals(other.optionalFields) && textSeparator.equals(other.textSeparator) - && csvDelimiter.equals(other.csvDelimiter); + && csvDelimiter.equals(other.csvDelimiter) + && dryRun.equals(other.dryRun); } @java.lang.Override public int hashCode() { return Objects.hash( - this.keepFields, - this.optionalFields, this.name, this.type, this.keepOriginalFile, this.skipMalformedInput, + this.keepFields, + this.optionalFields, this.textSeparator, - this.csvDelimiter); + this.csvDelimiter, + this.dryRun); } @java.lang.Override @@ -172,69 +184,45 @@ public static NameStage builder() { } public interface NameStage { - /** - *

The name of the uploaded dataset.

- */ TypeStage name(@NotNull String name); Builder from(DatasetsCreateRequest other); } public interface TypeStage { - /** - *

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

- */ _FinalStage type(@NotNull DatasetType type); } public interface _FinalStage { DatasetsCreateRequest build(); - /** - *

List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, datasets of type embed-input will drop all fields other than the required text field. If any of the fields in keep_fields are missing from the uploaded file, Dataset validation will fail.

- */ - _FinalStage keepFields(Optional> keepFields); - - _FinalStage keepFields(List keepFields); - - _FinalStage keepFields(String keepFields); - - /** - *

List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, Datasets of type embed-input will drop all fields other than the required text field. If any of the fields in optional_fields are missing from the uploaded file, Dataset validation will pass.

- */ - _FinalStage optionalFields(Optional> optionalFields); - - _FinalStage optionalFields(List optionalFields); - - _FinalStage optionalFields(String optionalFields); - - /** - *

Indicates if the original file should be stored.

- */ _FinalStage keepOriginalFile(Optional keepOriginalFile); _FinalStage keepOriginalFile(Boolean keepOriginalFile); - /** - *

Indicates whether rows with malformed input should be dropped (instead of failing the validation check). Dropped rows will be returned in the warnings field.

- */ _FinalStage skipMalformedInput(Optional skipMalformedInput); _FinalStage skipMalformedInput(Boolean skipMalformedInput); - /** - *

Raw .txt uploads will be split into entries using the text_separator value.

- */ + _FinalStage keepFields(Optional keepFields); + + _FinalStage keepFields(String keepFields); + + _FinalStage optionalFields(Optional optionalFields); + + _FinalStage optionalFields(String optionalFields); + _FinalStage textSeparator(Optional textSeparator); _FinalStage textSeparator(String textSeparator); - /** - *

The delimiter used for .csv uploads.

- */ _FinalStage csvDelimiter(Optional csvDelimiter); _FinalStage csvDelimiter(String csvDelimiter); + + _FinalStage dryRun(Optional dryRun); + + _FinalStage dryRun(Boolean dryRun); } @JsonIgnoreProperties(ignoreUnknown = true) @@ -243,17 +231,19 @@ public static final class Builder implements NameStage, TypeStage, _FinalStage { private DatasetType type; + private Optional dryRun = Optional.empty(); + private Optional csvDelimiter = Optional.empty(); private Optional textSeparator = Optional.empty(); - private Optional skipMalformedInput = Optional.empty(); + private Optional optionalFields = Optional.empty(); - private Optional keepOriginalFile = Optional.empty(); + private Optional keepFields = Optional.empty(); - private Optional> optionalFields = Optional.empty(); + private Optional skipMalformedInput = Optional.empty(); - private Optional> keepFields = Optional.empty(); + private Optional keepOriginalFile = Optional.empty(); @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -262,19 +252,19 @@ private Builder() {} @java.lang.Override public Builder from(DatasetsCreateRequest other) { - keepFields(other.getKeepFields()); - optionalFields(other.getOptionalFields()); name(other.getName()); type(other.getType()); keepOriginalFile(other.getKeepOriginalFile()); skipMalformedInput(other.getSkipMalformedInput()); + keepFields(other.getKeepFields()); + optionalFields(other.getOptionalFields()); textSeparator(other.getTextSeparator()); csvDelimiter(other.getCsvDelimiter()); + dryRun(other.getDryRun()); return this; } /** - *

The name of the uploaded dataset.

*

The name of the uploaded dataset.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -286,7 +276,6 @@ public TypeStage name(@NotNull String name) { } /** - *

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

*

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

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -298,18 +287,32 @@ public _FinalStage type(@NotNull DatasetType type) { } /** - *

The delimiter used for .csv uploads.

+ *

flag to enable dry_run mode

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage csvDelimiter(String csvDelimiter) { - this.csvDelimiter = Optional.ofNullable(csvDelimiter); + public _FinalStage dryRun(Boolean dryRun) { + this.dryRun = Optional.ofNullable(dryRun); + return this; + } + + @java.lang.Override + @JsonSetter(value = "dry_run", nulls = Nulls.SKIP) + public _FinalStage dryRun(Optional dryRun) { + this.dryRun = dryRun; return this; } /** *

The delimiter used for .csv uploads.

+ * @return Reference to {@code this} so that method calls can be chained together. */ + @java.lang.Override + public _FinalStage csvDelimiter(String csvDelimiter) { + this.csvDelimiter = Optional.ofNullable(csvDelimiter); + return this; + } + @java.lang.Override @JsonSetter(value = "csv_delimiter", nulls = Nulls.SKIP) public _FinalStage csvDelimiter(Optional csvDelimiter) { @@ -327,9 +330,6 @@ public _FinalStage textSeparator(String textSeparator) { return this; } - /** - *

Raw .txt uploads will be split into entries using the text_separator value.

- */ @java.lang.Override @JsonSetter(value = "text_separator", nulls = Nulls.SKIP) public _FinalStage textSeparator(Optional textSeparator) { @@ -338,108 +338,85 @@ public _FinalStage textSeparator(Optional textSeparator) { } /** - *

Indicates whether rows with malformed input should be dropped (instead of failing the validation check). Dropped rows will be returned in the warnings field.

+ *

List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, Datasets of type embed-input will drop all fields other than the required text field. If any of the fields in optional_fields are missing from the uploaded file, Dataset validation will pass.

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

Indicates whether rows with malformed input should be dropped (instead of failing the validation check). Dropped rows will be returned in the warnings field.

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

Indicates if the original file should be stored.

+ *

List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, datasets of type embed-input will drop all fields other than the required text field. If any of the fields in keep_fields are missing from the uploaded file, Dataset validation will fail.

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

Indicates if the original file should be stored.

- */ - @java.lang.Override - @JsonSetter(value = "keep_original_file", nulls = Nulls.SKIP) - public _FinalStage keepOriginalFile(Optional keepOriginalFile) { - this.keepOriginalFile = keepOriginalFile; + public _FinalStage keepFields(String keepFields) { + this.keepFields = Optional.ofNullable(keepFields); return this; } @java.lang.Override - public _FinalStage optionalFields(String optionalFields) { - this.optionalFields = Optional.of(Collections.singletonList(optionalFields)); + @JsonSetter(value = "keep_fields", nulls = Nulls.SKIP) + public _FinalStage keepFields(Optional keepFields) { + this.keepFields = keepFields; return this; } /** - *

List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, Datasets of type embed-input will drop all fields other than the required text field. If any of the fields in optional_fields are missing from the uploaded file, Dataset validation will pass.

+ *

Indicates whether rows with malformed input should be dropped (instead of failing the validation check). Dropped rows will be returned in the warnings field.

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

List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, Datasets of type embed-input will drop all fields other than the required text field. If any of the fields in optional_fields are missing from the uploaded file, Dataset validation will pass.

- */ - @java.lang.Override - @JsonSetter(value = "optional_fields", nulls = Nulls.SKIP) - public _FinalStage optionalFields(Optional> optionalFields) { - this.optionalFields = optionalFields; + public _FinalStage skipMalformedInput(Boolean skipMalformedInput) { + this.skipMalformedInput = Optional.ofNullable(skipMalformedInput); return this; } @java.lang.Override - public _FinalStage keepFields(String keepFields) { - this.keepFields = Optional.of(Collections.singletonList(keepFields)); + @JsonSetter(value = "skip_malformed_input", nulls = Nulls.SKIP) + public _FinalStage skipMalformedInput(Optional skipMalformedInput) { + this.skipMalformedInput = skipMalformedInput; return this; } /** - *

List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, datasets of type embed-input will drop all fields other than the required text field. If any of the fields in keep_fields are missing from the uploaded file, Dataset validation will fail.

+ *

Indicates if the original file should be stored.

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

List of names of fields that will be persisted in the Dataset. By default the Dataset will retain only the required fields indicated in the schema for the corresponding Dataset type. For example, datasets of type embed-input will drop all fields other than the required text field. If any of the fields in keep_fields are missing from the uploaded file, Dataset validation will fail.

- */ @java.lang.Override - @JsonSetter(value = "keep_fields", nulls = Nulls.SKIP) - public _FinalStage keepFields(Optional> keepFields) { - this.keepFields = keepFields; + @JsonSetter(value = "keep_original_file", nulls = Nulls.SKIP) + public _FinalStage keepOriginalFile(Optional keepOriginalFile) { + this.keepOriginalFile = keepOriginalFile; return this; } @java.lang.Override public DatasetsCreateRequest build() { return new DatasetsCreateRequest( - keepFields, - optionalFields, name, type, keepOriginalFile, skipMalformedInput, + keepFields, + optionalFields, textSeparator, csvDelimiter, + dryRun, additionalProperties); } } diff --git a/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsListRequest.java b/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsListRequest.java index 551c7ee..f3cb529 100644 --- a/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsListRequest.java +++ b/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsListRequest.java @@ -164,9 +164,6 @@ public Builder from(DatasetsListRequest other) { return this; } - /** - *

optional filter by dataset type

- */ @JsonSetter(value = "datasetType", nulls = Nulls.SKIP) public Builder datasetType(Optional datasetType) { this.datasetType = datasetType; @@ -178,9 +175,6 @@ public Builder datasetType(String datasetType) { return this; } - /** - *

optional filter before a date

- */ @JsonSetter(value = "before", nulls = Nulls.SKIP) public Builder before(Optional before) { this.before = before; @@ -192,9 +186,6 @@ public Builder before(OffsetDateTime before) { return this; } - /** - *

optional filter after a date

- */ @JsonSetter(value = "after", nulls = Nulls.SKIP) public Builder after(Optional after) { this.after = after; @@ -206,9 +197,6 @@ public Builder after(OffsetDateTime after) { return this; } - /** - *

optional limit to number of results

- */ @JsonSetter(value = "limit", nulls = Nulls.SKIP) public Builder limit(Optional limit) { this.limit = limit; @@ -220,9 +208,6 @@ public Builder limit(Double limit) { return this; } - /** - *

optional offset to start of results

- */ @JsonSetter(value = "offset", nulls = Nulls.SKIP) public Builder offset(Optional offset) { this.offset = offset; @@ -234,9 +219,6 @@ public Builder offset(Double offset) { return this; } - /** - *

optional filter by validation status

- */ @JsonSetter(value = "validationStatus", nulls = Nulls.SKIP) public Builder validationStatus(Optional validationStatus) { this.validationStatus = validationStatus; diff --git a/src/main/java/com/cohere/api/resources/datasets/types/DatasetsCreateResponse.java b/src/main/java/com/cohere/api/resources/datasets/types/DatasetsCreateResponse.java index 840ae1a..4c19ac4 100644 --- a/src/main/java/com/cohere/api/resources/datasets/types/DatasetsCreateResponse.java +++ b/src/main/java/com/cohere/api/resources/datasets/types/DatasetsCreateResponse.java @@ -80,9 +80,6 @@ public Builder from(DatasetsCreateResponse other) { return this; } - /** - *

The dataset ID

- */ @JsonSetter(value = "id", nulls = Nulls.SKIP) public Builder id(Optional id) { this.id = id; diff --git a/src/main/java/com/cohere/api/resources/datasets/types/DatasetsCreateResponseDatasetPartsItem.java b/src/main/java/com/cohere/api/resources/datasets/types/DatasetsCreateResponseDatasetPartsItem.java new file mode 100644 index 0000000..011ac8a --- /dev/null +++ b/src/main/java/com/cohere/api/resources/datasets/types/DatasetsCreateResponseDatasetPartsItem.java @@ -0,0 +1,180 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.datasets.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DatasetsCreateResponseDatasetPartsItem.Builder.class) +public final class DatasetsCreateResponseDatasetPartsItem { + private final Optional name; + + private final Optional numRows; + + private final Optional> samples; + + private final Optional partKind; + + private final Map additionalProperties; + + private DatasetsCreateResponseDatasetPartsItem( + Optional name, + Optional numRows, + Optional> samples, + Optional partKind, + Map additionalProperties) { + this.name = name; + this.numRows = numRows; + this.samples = samples; + this.partKind = partKind; + this.additionalProperties = additionalProperties; + } + + /** + * @return the name of the dataset part + */ + @JsonProperty("name") + public Optional getName() { + return name; + } + + /** + * @return the number of rows in the dataset part + */ + @JsonProperty("num_rows") + public Optional getNumRows() { + return numRows; + } + + @JsonProperty("samples") + public Optional> getSamples() { + return samples; + } + + /** + * @return the kind of dataset part + */ + @JsonProperty("part_kind") + public Optional getPartKind() { + return partKind; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DatasetsCreateResponseDatasetPartsItem + && equalTo((DatasetsCreateResponseDatasetPartsItem) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DatasetsCreateResponseDatasetPartsItem other) { + return name.equals(other.name) + && numRows.equals(other.numRows) + && samples.equals(other.samples) + && partKind.equals(other.partKind); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.name, this.numRows, this.samples, this.partKind); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional name = Optional.empty(); + + private Optional numRows = Optional.empty(); + + private Optional> samples = Optional.empty(); + + private Optional partKind = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DatasetsCreateResponseDatasetPartsItem other) { + name(other.getName()); + numRows(other.getNumRows()); + samples(other.getSamples()); + partKind(other.getPartKind()); + return this; + } + + @JsonSetter(value = "name", nulls = Nulls.SKIP) + public Builder name(Optional name) { + this.name = name; + return this; + } + + public Builder name(String name) { + this.name = Optional.ofNullable(name); + return this; + } + + @JsonSetter(value = "num_rows", nulls = Nulls.SKIP) + public Builder numRows(Optional numRows) { + this.numRows = numRows; + return this; + } + + public Builder numRows(Double numRows) { + this.numRows = Optional.ofNullable(numRows); + return this; + } + + @JsonSetter(value = "samples", nulls = Nulls.SKIP) + public Builder samples(Optional> samples) { + this.samples = samples; + return this; + } + + public Builder samples(List samples) { + this.samples = Optional.ofNullable(samples); + return this; + } + + @JsonSetter(value = "part_kind", nulls = Nulls.SKIP) + public Builder partKind(Optional partKind) { + this.partKind = partKind; + return this; + } + + public Builder partKind(String partKind) { + this.partKind = Optional.ofNullable(partKind); + return this; + } + + public DatasetsCreateResponseDatasetPartsItem build() { + return new DatasetsCreateResponseDatasetPartsItem(name, numRows, samples, partKind, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/resources/datasets/types/DatasetsGetUsageResponse.java b/src/main/java/com/cohere/api/resources/datasets/types/DatasetsGetUsageResponse.java index 7e7e343..637ce73 100644 --- a/src/main/java/com/cohere/api/resources/datasets/types/DatasetsGetUsageResponse.java +++ b/src/main/java/com/cohere/api/resources/datasets/types/DatasetsGetUsageResponse.java @@ -80,9 +80,6 @@ public Builder from(DatasetsGetUsageResponse other) { return this; } - /** - *

The total number of bytes used by the organization.

- */ @JsonSetter(value = "organization_usage", nulls = Nulls.SKIP) public Builder organizationUsage(Optional organizationUsage) { this.organizationUsage = organizationUsage; diff --git a/src/main/java/com/cohere/api/resources/embedjobs/AsyncEmbedJobsClient.java b/src/main/java/com/cohere/api/resources/embedjobs/AsyncEmbedJobsClient.java deleted file mode 100644 index 3b49202..0000000 --- a/src/main/java/com/cohere/api/resources/embedjobs/AsyncEmbedJobsClient.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.embedjobs; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.resources.embedjobs.requests.CreateEmbedJobRequest; -import com.cohere.api.types.CreateEmbedJobResponse; -import com.cohere.api.types.EmbedJob; -import com.cohere.api.types.ListEmbedJobResponse; -import java.util.concurrent.CompletableFuture; - -public class AsyncEmbedJobsClient { - protected final ClientOptions clientOptions; - - private final AsyncRawEmbedJobsClient rawClient; - - public AsyncEmbedJobsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawEmbedJobsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawEmbedJobsClient withRawResponse() { - return this.rawClient; - } - - /** - * The list embed job endpoint allows users to view all embed jobs history for that specific user. - */ - public CompletableFuture list() { - return this.rawClient.list().thenApply(response -> response.body()); - } - - /** - * The list embed job endpoint allows users to view all embed jobs history for that specific user. - */ - public CompletableFuture list(RequestOptions requestOptions) { - return this.rawClient.list(requestOptions).thenApply(response -> response.body()); - } - - /** - * This API launches an async Embed job for a Dataset of type embed-input. The result of a completed embed job is new Dataset of type embed-output, which contains the original text entries and the corresponding embeddings. - */ - public CompletableFuture create(CreateEmbedJobRequest request) { - return this.rawClient.create(request).thenApply(response -> response.body()); - } - - /** - * This API launches an async Embed job for a Dataset of type embed-input. The result of a completed embed job is new Dataset of type embed-output, which contains the original text entries and the corresponding embeddings. - */ - public CompletableFuture create( - CreateEmbedJobRequest request, RequestOptions requestOptions) { - return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * This API retrieves the details about an embed job started by the same user. - */ - public CompletableFuture get(String id) { - return this.rawClient.get(id).thenApply(response -> response.body()); - } - - /** - * This API retrieves the details about an embed job started by the same user. - */ - public CompletableFuture get(String id, RequestOptions requestOptions) { - return this.rawClient.get(id, requestOptions).thenApply(response -> response.body()); - } - - /** - * This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation. - */ - public CompletableFuture cancel(String id) { - return this.rawClient.cancel(id).thenApply(response -> response.body()); - } - - /** - * This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation. - */ - public CompletableFuture cancel(String id, RequestOptions requestOptions) { - return this.rawClient.cancel(id, requestOptions).thenApply(response -> response.body()); - } -} diff --git a/src/main/java/com/cohere/api/resources/embedjobs/AsyncRawEmbedJobsClient.java b/src/main/java/com/cohere/api/resources/embedjobs/AsyncRawEmbedJobsClient.java deleted file mode 100644 index eb7a551..0000000 --- a/src/main/java/com/cohere/api/resources/embedjobs/AsyncRawEmbedJobsClient.java +++ /dev/null @@ -1,547 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.embedjobs; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.embedjobs.requests.CreateEmbedJobRequest; -import com.cohere.api.types.CreateEmbedJobResponse; -import com.cohere.api.types.EmbedJob; -import com.cohere.api.types.ListEmbedJobResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import java.io.IOException; -import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; - -public class AsyncRawEmbedJobsClient { - protected final ClientOptions clientOptions; - - public AsyncRawEmbedJobsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * The list embed job endpoint allows users to view all embed jobs history for that specific user. - */ - public CompletableFuture> list() { - return list(null); - } - - /** - * The list embed job endpoint allows users to view all embed jobs history for that specific user. - */ - public CompletableFuture> list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed-jobs") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEmbedJobResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This API launches an async Embed job for a Dataset of type embed-input. The result of a completed embed job is new Dataset of type embed-output, which contains the original text entries and the corresponding embeddings. - */ - public CompletableFuture> create(CreateEmbedJobRequest request) { - return create(request, null); - } - - /** - * This API launches an async Embed job for a Dataset of type embed-input. The result of a completed embed job is new Dataset of type embed-output, which contains the original text entries and the corresponding embeddings. - */ - public CompletableFuture> create( - CreateEmbedJobRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed-jobs") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), CreateEmbedJobResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This API retrieves the details about an embed job started by the same user. - */ - public CompletableFuture> get(String id) { - return get(id, null); - } - - /** - * This API retrieves the details about an embed job started by the same user. - */ - public CompletableFuture> get(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed-jobs") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedJob.class), response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation. - */ - public CompletableFuture> cancel(String id) { - return cancel(id, null); - } - - /** - * This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation. - */ - public CompletableFuture> cancel(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed-jobs") - .addPathSegment(id) - .addPathSegments("cancel") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>(null, response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/src/main/java/com/cohere/api/resources/embedjobs/EmbedJobsClient.java b/src/main/java/com/cohere/api/resources/embedjobs/EmbedJobsClient.java index 68d30ec..e3ef4d2 100644 --- a/src/main/java/com/cohere/api/resources/embedjobs/EmbedJobsClient.java +++ b/src/main/java/com/cohere/api/resources/embedjobs/EmbedJobsClient.java @@ -4,82 +4,370 @@ package com.cohere.api.resources.embedjobs; import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.CohereApiException; +import com.cohere.api.core.CohereException; +import com.cohere.api.core.MediaTypes; +import com.cohere.api.core.ObjectMappers; import com.cohere.api.core.RequestOptions; +import com.cohere.api.errors.BadRequestError; +import com.cohere.api.errors.ClientClosedRequestError; +import com.cohere.api.errors.ForbiddenError; +import com.cohere.api.errors.GatewayTimeoutError; +import com.cohere.api.errors.InternalServerError; +import com.cohere.api.errors.InvalidTokenError; +import com.cohere.api.errors.NotFoundError; +import com.cohere.api.errors.NotImplementedError; +import com.cohere.api.errors.ServiceUnavailableError; +import com.cohere.api.errors.TooManyRequestsError; +import com.cohere.api.errors.UnauthorizedError; +import com.cohere.api.errors.UnprocessableEntityError; import com.cohere.api.resources.embedjobs.requests.CreateEmbedJobRequest; import com.cohere.api.types.CreateEmbedJobResponse; import com.cohere.api.types.EmbedJob; import com.cohere.api.types.ListEmbedJobResponse; +import com.fasterxml.jackson.core.JsonProcessingException; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class EmbedJobsClient { protected final ClientOptions clientOptions; - private final RawEmbedJobsClient rawClient; - public EmbedJobsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; - this.rawClient = new RawEmbedJobsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawEmbedJobsClient withRawResponse() { - return this.rawClient; } /** * The list embed job endpoint allows users to view all embed jobs history for that specific user. */ public ListEmbedJobResponse list() { - return this.rawClient.list().body(); + return list(null); } /** * The list embed job endpoint allows users to view all embed jobs history for that specific user. */ public ListEmbedJobResponse list(RequestOptions requestOptions) { - return this.rawClient.list(requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/embed-jobs") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEmbedJobResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * This API launches an async Embed job for a Dataset of type embed-input. The result of a completed embed job is new Dataset of type embed-output, which contains the original text entries and the corresponding embeddings. */ public CreateEmbedJobResponse create(CreateEmbedJobRequest request) { - return this.rawClient.create(request).body(); + return create(request, null); } /** * This API launches an async Embed job for a Dataset of type embed-input. The result of a completed embed job is new Dataset of type embed-output, which contains the original text entries and the corresponding embeddings. */ public CreateEmbedJobResponse create(CreateEmbedJobRequest request, RequestOptions requestOptions) { - return this.rawClient.create(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/embed-jobs") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateEmbedJobResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * This API retrieves the details about an embed job started by the same user. */ public EmbedJob get(String id) { - return this.rawClient.get(id).body(); + return get(id, null); } /** * This API retrieves the details about an embed job started by the same user. */ public EmbedJob get(String id, RequestOptions requestOptions) { - return this.rawClient.get(id, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/embed-jobs") + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedJob.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation. */ public void cancel(String id) { - this.rawClient.cancel(id).body(); + cancel(id, null); } /** * This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation. */ public void cancel(String id, RequestOptions requestOptions) { - this.rawClient.cancel(id, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/embed-jobs") + .addPathSegment(id) + .addPathSegments("cancel") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw 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 deleted file mode 100644 index cecf37f..0000000 --- a/src/main/java/com/cohere/api/resources/embedjobs/RawEmbedJobsClient.java +++ /dev/null @@ -1,394 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.embedjobs; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.embedjobs.requests.CreateEmbedJobRequest; -import com.cohere.api.types.CreateEmbedJobResponse; -import com.cohere.api.types.EmbedJob; -import com.cohere.api.types.ListEmbedJobResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; - -public class RawEmbedJobsClient { - protected final ClientOptions clientOptions; - - public RawEmbedJobsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * The list embed job endpoint allows users to view all embed jobs history for that specific user. - */ - public CohereHttpResponse list() { - return list(null); - } - - /** - * The list embed job endpoint allows users to view all embed jobs history for that specific user. - */ - public CohereHttpResponse list(RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed-jobs") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEmbedJobResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This API launches an async Embed job for a Dataset of type embed-input. The result of a completed embed job is new Dataset of type embed-output, which contains the original text entries and the corresponding embeddings. - */ - public CohereHttpResponse create(CreateEmbedJobRequest request) { - return create(request, null); - } - - /** - * This API launches an async Embed job for a Dataset of type embed-input. The result of a completed embed job is new Dataset of type embed-output, which contains the original text entries and the corresponding embeddings. - */ - public CohereHttpResponse create( - CreateEmbedJobRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed-jobs") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateEmbedJobResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This API retrieves the details about an embed job started by the same user. - */ - public CohereHttpResponse get(String id) { - return get(id, null); - } - - /** - * This API retrieves the details about an embed job started by the same user. - */ - public CohereHttpResponse get(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed-jobs") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedJob.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation. - */ - public CohereHttpResponse cancel(String id) { - return cancel(id, null); - } - - /** - * This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation. - */ - public CohereHttpResponse cancel(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/embed-jobs") - .addPathSegment(id) - .addPathSegments("cancel") - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", RequestBody.create("", null)) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>(null, response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } -} diff --git a/src/main/java/com/cohere/api/resources/embedjobs/requests/CreateEmbedJobRequest.java b/src/main/java/com/cohere/api/resources/embedjobs/requests/CreateEmbedJobRequest.java index 9ec058c..29e2bc5 100644 --- a/src/main/java/com/cohere/api/resources/embedjobs/requests/CreateEmbedJobRequest.java +++ b/src/main/java/com/cohere/api/resources/embedjobs/requests/CreateEmbedJobRequest.java @@ -151,25 +151,12 @@ public static ModelStage builder() { } public interface ModelStage { - /** - *

ID of the embedding model.

- *

Available models and corresponding embedding dimensions:

- *
    - *
  • embed-english-v3.0 : 1024
  • - *
  • embed-multilingual-v3.0 : 1024
  • - *
  • embed-english-light-v3.0 : 384
  • - *
  • embed-multilingual-light-v3.0 : 384
  • - *
- */ DatasetIdStage model(@NotNull String model); Builder from(CreateEmbedJobRequest other); } public interface DatasetIdStage { - /** - *

ID of a Dataset. The Dataset must be of type embed-input and must have a validation status Validated

- */ InputTypeStage datasetId(@NotNull String datasetId); } @@ -180,31 +167,14 @@ public interface InputTypeStage { public interface _FinalStage { CreateEmbedJobRequest build(); - /** - *

The name of the embed job.

- */ _FinalStage name(Optional name); _FinalStage name(String name); - /** - *

Specifies the types of embeddings you want to get back. Not required and default is None, which returns the Embed Floats response type. Can be one or more of the following types.

- *
    - *
  • "float": Use this when you want to get back the default float embeddings. Valid for all models.
  • - *
  • "int8": Use this when you want to get back signed int8 embeddings. Valid for v3 and newer model versions.
  • - *
  • "uint8": Use this when you want to get back unsigned int8 embeddings. Valid for v3 and newer model versions.
  • - *
  • "binary": Use this when you want to get back signed binary embeddings. Valid for v3 and newer model versions.
  • - *
  • "ubinary": Use this when you want to get back unsigned binary embeddings. Valid for v3 and newer model versions.
  • - *
- */ _FinalStage embeddingTypes(Optional> embeddingTypes); _FinalStage embeddingTypes(List embeddingTypes); - /** - *

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

- *

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

- */ _FinalStage truncate(Optional truncate); _FinalStage truncate(CreateEmbedJobRequestTruncate truncate); @@ -241,14 +211,6 @@ public Builder from(CreateEmbedJobRequest other) { } /** - *

ID of the embedding model.

- *

Available models and corresponding embedding dimensions:

- *
    - *
  • embed-english-v3.0 : 1024
  • - *
  • embed-multilingual-v3.0 : 1024
  • - *
  • embed-english-light-v3.0 : 384
  • - *
  • embed-multilingual-light-v3.0 : 384
  • - *
*

ID of the embedding model.

*

Available models and corresponding embedding dimensions:

*
    @@ -267,7 +229,6 @@ public DatasetIdStage model(@NotNull String model) { } /** - *

    ID of a Dataset. The Dataset must be of type embed-input and must have a validation status Validated

    *

    ID of a Dataset. The Dataset must be of type embed-input and must have a validation status Validated

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -296,10 +257,6 @@ public _FinalStage truncate(CreateEmbedJobRequestTruncate truncate) { return this; } - /** - *

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

    - *

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

    - */ @java.lang.Override @JsonSetter(value = "truncate", nulls = Nulls.SKIP) public _FinalStage truncate(Optional truncate) { @@ -324,16 +281,6 @@ public _FinalStage embeddingTypes(List embeddingTypes) { return this; } - /** - *

    Specifies the types of embeddings you want to get back. Not required and default is None, which returns the Embed Floats response type. Can be one or more of the following types.

    - *
      - *
    • "float": Use this when you want to get back the default float embeddings. Valid for all models.
    • - *
    • "int8": Use this when you want to get back signed int8 embeddings. Valid for v3 and newer model versions.
    • - *
    • "uint8": Use this when you want to get back unsigned int8 embeddings. Valid for v3 and newer model versions.
    • - *
    • "binary": Use this when you want to get back signed binary embeddings. Valid for v3 and newer model versions.
    • - *
    • "ubinary": Use this when you want to get back unsigned binary embeddings. Valid for v3 and newer model versions.
    • - *
    - */ @java.lang.Override @JsonSetter(value = "embedding_types", nulls = Nulls.SKIP) public _FinalStage embeddingTypes(Optional> embeddingTypes) { @@ -351,9 +298,6 @@ public _FinalStage name(String name) { return this; } - /** - *

    The name of the embed job.

    - */ @java.lang.Override @JsonSetter(value = "name", nulls = Nulls.SKIP) public _FinalStage name(Optional name) { diff --git a/src/main/java/com/cohere/api/resources/finetuning/AsyncFinetuningClient.java b/src/main/java/com/cohere/api/resources/finetuning/AsyncFinetuningClient.java deleted file mode 100644 index a237b35..0000000 --- a/src/main/java/com/cohere/api/resources/finetuning/AsyncFinetuningClient.java +++ /dev/null @@ -1,184 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.finetuning; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.resources.finetuning.finetuning.types.CreateFinetunedModelResponse; -import com.cohere.api.resources.finetuning.finetuning.types.FinetunedModel; -import com.cohere.api.resources.finetuning.finetuning.types.GetFinetunedModelResponse; -import com.cohere.api.resources.finetuning.finetuning.types.ListEventsResponse; -import com.cohere.api.resources.finetuning.finetuning.types.ListFinetunedModelsResponse; -import com.cohere.api.resources.finetuning.finetuning.types.ListTrainingStepMetricsResponse; -import com.cohere.api.resources.finetuning.finetuning.types.UpdateFinetunedModelResponse; -import com.cohere.api.resources.finetuning.requests.FinetuningListEventsRequest; -import com.cohere.api.resources.finetuning.requests.FinetuningListFinetunedModelsRequest; -import com.cohere.api.resources.finetuning.requests.FinetuningListTrainingStepMetricsRequest; -import com.cohere.api.resources.finetuning.requests.FinetuningUpdateFinetunedModelRequest; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -public class AsyncFinetuningClient { - protected final ClientOptions clientOptions; - - private final AsyncRawFinetuningClient rawClient; - - public AsyncFinetuningClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawFinetuningClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawFinetuningClient withRawResponse() { - return this.rawClient; - } - - /** - * Returns a list of fine-tuned models that the user has access to. - */ - public CompletableFuture listFinetunedModels() { - return this.rawClient.listFinetunedModels().thenApply(response -> response.body()); - } - - /** - * Returns a list of fine-tuned models that the user has access to. - */ - public CompletableFuture listFinetunedModels( - FinetuningListFinetunedModelsRequest request) { - return this.rawClient.listFinetunedModels(request).thenApply(response -> response.body()); - } - - /** - * Returns a list of fine-tuned models that the user has access to. - */ - public CompletableFuture listFinetunedModels( - FinetuningListFinetunedModelsRequest request, RequestOptions requestOptions) { - return this.rawClient.listFinetunedModels(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Creates a new fine-tuned model. The model will be trained on the dataset specified in the request body. The training process may take some time, and the model will be available once the training is complete. - */ - public CompletableFuture createFinetunedModel(FinetunedModel request) { - return this.rawClient.createFinetunedModel(request).thenApply(response -> response.body()); - } - - /** - * Creates a new fine-tuned model. The model will be trained on the dataset specified in the request body. The training process may take some time, and the model will be available once the training is complete. - */ - public CompletableFuture createFinetunedModel( - FinetunedModel request, RequestOptions requestOptions) { - return this.rawClient.createFinetunedModel(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Retrieve a fine-tuned model by its ID. - */ - public CompletableFuture getFinetunedModel(String id) { - return this.rawClient.getFinetunedModel(id).thenApply(response -> response.body()); - } - - /** - * Retrieve a fine-tuned model by its ID. - */ - public CompletableFuture getFinetunedModel(String id, RequestOptions requestOptions) { - return this.rawClient.getFinetunedModel(id, requestOptions).thenApply(response -> response.body()); - } - - /** - * Deletes a fine-tuned model. The model will be removed from the system and will no longer be available for use. - * This operation is irreversible. - */ - public CompletableFuture> deleteFinetunedModel(String id) { - return this.rawClient.deleteFinetunedModel(id).thenApply(response -> response.body()); - } - - /** - * Deletes a fine-tuned model. The model will be removed from the system and will no longer be available for use. - * This operation is irreversible. - */ - public CompletableFuture> deleteFinetunedModel(String id, RequestOptions requestOptions) { - return this.rawClient.deleteFinetunedModel(id, requestOptions).thenApply(response -> response.body()); - } - - /** - * Updates the fine-tuned model with the given ID. The model will be updated with the new settings and name provided in the request body. - */ - public CompletableFuture updateFinetunedModel( - String id, FinetuningUpdateFinetunedModelRequest request) { - return this.rawClient.updateFinetunedModel(id, request).thenApply(response -> response.body()); - } - - /** - * Updates the fine-tuned model with the given ID. The model will be updated with the new settings and name provided in the request body. - */ - public CompletableFuture updateFinetunedModel( - String id, FinetuningUpdateFinetunedModelRequest request, RequestOptions requestOptions) { - return this.rawClient.updateFinetunedModel(id, request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Returns a list of events that occurred during the life-cycle of the fine-tuned model. - * The events are ordered by creation time, with the most recent event first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture listEvents(String finetunedModelId) { - return this.rawClient.listEvents(finetunedModelId).thenApply(response -> response.body()); - } - - /** - * Returns a list of events that occurred during the life-cycle of the fine-tuned model. - * The events are ordered by creation time, with the most recent event first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture listEvents( - String finetunedModelId, FinetuningListEventsRequest request) { - return this.rawClient.listEvents(finetunedModelId, request).thenApply(response -> response.body()); - } - - /** - * Returns a list of events that occurred during the life-cycle of the fine-tuned model. - * The events are ordered by creation time, with the most recent event first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture listEvents( - String finetunedModelId, FinetuningListEventsRequest request, RequestOptions requestOptions) { - return this.rawClient - .listEvents(finetunedModelId, request, requestOptions) - .thenApply(response -> response.body()); - } - - /** - * Returns a list of metrics measured during the training of a fine-tuned model. - * The metrics are ordered by step number, with the most recent step first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture listTrainingStepMetrics(String finetunedModelId) { - return this.rawClient.listTrainingStepMetrics(finetunedModelId).thenApply(response -> response.body()); - } - - /** - * Returns a list of metrics measured during the training of a fine-tuned model. - * The metrics are ordered by step number, with the most recent step first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture listTrainingStepMetrics( - String finetunedModelId, FinetuningListTrainingStepMetricsRequest request) { - return this.rawClient.listTrainingStepMetrics(finetunedModelId, request).thenApply(response -> response.body()); - } - - /** - * Returns a list of metrics measured during the training of a fine-tuned model. - * The metrics are ordered by step number, with the most recent step first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture listTrainingStepMetrics( - String finetunedModelId, FinetuningListTrainingStepMetricsRequest request, RequestOptions requestOptions) { - return this.rawClient - .listTrainingStepMetrics(finetunedModelId, request, requestOptions) - .thenApply(response -> response.body()); - } -} diff --git a/src/main/java/com/cohere/api/resources/finetuning/AsyncRawFinetuningClient.java b/src/main/java/com/cohere/api/resources/finetuning/AsyncRawFinetuningClient.java deleted file mode 100644 index 2f1e153..0000000 --- a/src/main/java/com/cohere/api/resources/finetuning/AsyncRawFinetuningClient.java +++ /dev/null @@ -1,807 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.finetuning; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.QueryStringMapper; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.resources.finetuning.finetuning.types.CreateFinetunedModelResponse; -import com.cohere.api.resources.finetuning.finetuning.types.FinetunedModel; -import com.cohere.api.resources.finetuning.finetuning.types.GetFinetunedModelResponse; -import com.cohere.api.resources.finetuning.finetuning.types.ListEventsResponse; -import com.cohere.api.resources.finetuning.finetuning.types.ListFinetunedModelsResponse; -import com.cohere.api.resources.finetuning.finetuning.types.ListTrainingStepMetricsResponse; -import com.cohere.api.resources.finetuning.finetuning.types.UpdateFinetunedModelResponse; -import com.cohere.api.resources.finetuning.requests.FinetuningListEventsRequest; -import com.cohere.api.resources.finetuning.requests.FinetuningListFinetunedModelsRequest; -import com.cohere.api.resources.finetuning.requests.FinetuningListTrainingStepMetricsRequest; -import com.cohere.api.resources.finetuning.requests.FinetuningUpdateFinetunedModelRequest; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; - -public class AsyncRawFinetuningClient { - protected final ClientOptions clientOptions; - - public AsyncRawFinetuningClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Returns a list of fine-tuned models that the user has access to. - */ - public CompletableFuture> listFinetunedModels() { - return listFinetunedModels( - FinetuningListFinetunedModelsRequest.builder().build()); - } - - /** - * Returns a list of fine-tuned models that the user has access to. - */ - public CompletableFuture> listFinetunedModels( - FinetuningListFinetunedModelsRequest request) { - return listFinetunedModels(request, null); - } - - /** - * Returns a list of fine-tuned models that the user has access to. - */ - public CompletableFuture> listFinetunedModels( - FinetuningListFinetunedModelsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models"); - if (request.getPageSize().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_size", request.getPageSize().get(), false); - } - if (request.getPageToken().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_token", request.getPageToken().get(), false); - } - if (request.getOrderBy().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "order_by", request.getOrderBy().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ListFinetunedModelsResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Creates a new fine-tuned model. The model will be trained on the dataset specified in the request body. The training process may take some time, and the model will be available once the training is complete. - */ - public CompletableFuture> createFinetunedModel( - FinetunedModel request) { - return createFinetunedModel(request, null); - } - - /** - * Creates a new fine-tuned model. The model will be trained on the dataset specified in the request body. The training process may take some time, and the model will be available once the training is complete. - */ - public CompletableFuture> createFinetunedModel( - FinetunedModel request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), CreateFinetunedModelResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Retrieve a fine-tuned model by its ID. - */ - public CompletableFuture> getFinetunedModel(String id) { - return getFinetunedModel(id, null); - } - - /** - * Retrieve a fine-tuned model by its ID. - */ - public CompletableFuture> getFinetunedModel( - String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), GetFinetunedModelResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Deletes a fine-tuned model. The model will be removed from the system and will no longer be available for use. - * This operation is irreversible. - */ - public CompletableFuture>> deleteFinetunedModel(String id) { - return deleteFinetunedModel(id, null); - } - - /** - * Deletes a fine-tuned model. The model will be removed from the system and will no longer be available for use. - * This operation is irreversible. - */ - public CompletableFuture>> deleteFinetunedModel( - String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture>> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Updates the fine-tuned model with the given ID. The model will be updated with the new settings and name provided in the request body. - */ - public CompletableFuture> updateFinetunedModel( - String id, FinetuningUpdateFinetunedModelRequest request) { - return updateFinetunedModel(id, request, null); - } - - /** - * Updates the fine-tuned model with the given ID. The model will be updated with the new settings and name provided in the request body. - */ - public CompletableFuture> updateFinetunedModel( - String id, FinetuningUpdateFinetunedModelRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(id) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PATCH", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), UpdateFinetunedModelResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Returns a list of events that occurred during the life-cycle of the fine-tuned model. - * The events are ordered by creation time, with the most recent event first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture> listEvents(String finetunedModelId) { - return listEvents( - finetunedModelId, FinetuningListEventsRequest.builder().build()); - } - - /** - * Returns a list of events that occurred during the life-cycle of the fine-tuned model. - * The events are ordered by creation time, with the most recent event first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture> listEvents( - String finetunedModelId, FinetuningListEventsRequest request) { - return listEvents(finetunedModelId, request, null); - } - - /** - * Returns a list of events that occurred during the life-cycle of the fine-tuned model. - * The events are ordered by creation time, with the most recent event first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture> listEvents( - String finetunedModelId, FinetuningListEventsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(finetunedModelId) - .addPathSegments("events"); - if (request.getPageSize().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_size", request.getPageSize().get(), false); - } - if (request.getPageToken().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_token", request.getPageToken().get(), false); - } - if (request.getOrderBy().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "order_by", request.getOrderBy().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEventsResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Returns a list of metrics measured during the training of a fine-tuned model. - * The metrics are ordered by step number, with the most recent step first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture> listTrainingStepMetrics( - String finetunedModelId) { - return listTrainingStepMetrics( - finetunedModelId, - FinetuningListTrainingStepMetricsRequest.builder().build()); - } - - /** - * Returns a list of metrics measured during the training of a fine-tuned model. - * The metrics are ordered by step number, with the most recent step first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture> listTrainingStepMetrics( - String finetunedModelId, FinetuningListTrainingStepMetricsRequest request) { - return listTrainingStepMetrics(finetunedModelId, request, null); - } - - /** - * Returns a list of metrics measured during the training of a fine-tuned model. - * The metrics are ordered by step number, with the most recent step first. - * The list can be paginated using page_size and page_token parameters. - */ - public CompletableFuture> listTrainingStepMetrics( - String finetunedModelId, FinetuningListTrainingStepMetricsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(finetunedModelId) - .addPathSegments("training-step-metrics"); - if (request.getPageSize().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_size", request.getPageSize().get(), false); - } - if (request.getPageToken().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_token", request.getPageToken().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ListTrainingStepMetricsResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/src/main/java/com/cohere/api/resources/finetuning/FinetuningClient.java b/src/main/java/com/cohere/api/resources/finetuning/FinetuningClient.java index b26fd12..9c10f99 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/FinetuningClient.java +++ b/src/main/java/com/cohere/api/resources/finetuning/FinetuningClient.java @@ -4,7 +4,17 @@ package com.cohere.api.resources.finetuning; import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.CohereApiException; +import com.cohere.api.core.CohereException; +import com.cohere.api.core.MediaTypes; +import com.cohere.api.core.ObjectMappers; import com.cohere.api.core.RequestOptions; +import com.cohere.api.errors.BadRequestError; +import com.cohere.api.errors.ForbiddenError; +import com.cohere.api.errors.InternalServerError; +import com.cohere.api.errors.NotFoundError; +import com.cohere.api.errors.ServiceUnavailableError; +import com.cohere.api.errors.UnauthorizedError; import com.cohere.api.resources.finetuning.finetuning.types.CreateFinetunedModelResponse; import com.cohere.api.resources.finetuning.finetuning.types.FinetunedModel; import com.cohere.api.resources.finetuning.finetuning.types.GetFinetunedModelResponse; @@ -16,37 +26,38 @@ import com.cohere.api.resources.finetuning.requests.FinetuningListFinetunedModelsRequest; import com.cohere.api.resources.finetuning.requests.FinetuningListTrainingStepMetricsRequest; import com.cohere.api.resources.finetuning.requests.FinetuningUpdateFinetunedModelRequest; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import java.io.IOException; import java.util.Map; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class FinetuningClient { protected final ClientOptions clientOptions; - private final RawFinetuningClient rawClient; - public FinetuningClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; - this.rawClient = new RawFinetuningClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawFinetuningClient withRawResponse() { - return this.rawClient; } /** * Returns a list of fine-tuned models that the user has access to. */ public ListFinetunedModelsResponse listFinetunedModels() { - return this.rawClient.listFinetunedModels().body(); + return listFinetunedModels( + FinetuningListFinetunedModelsRequest.builder().build()); } /** * Returns a list of fine-tuned models that the user has access to. */ public ListFinetunedModelsResponse listFinetunedModels(FinetuningListFinetunedModelsRequest request) { - return this.rawClient.listFinetunedModels(request).body(); + return listFinetunedModels(request, null); } /** @@ -54,35 +65,195 @@ public ListFinetunedModelsResponse listFinetunedModels(FinetuningListFinetunedMo */ public ListFinetunedModelsResponse listFinetunedModels( FinetuningListFinetunedModelsRequest request, RequestOptions requestOptions) { - return this.rawClient.listFinetunedModels(request, requestOptions).body(); + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/finetuning/finetuned-models"); + if (request.getPageSize().isPresent()) { + httpUrl.addQueryParameter("page_size", request.getPageSize().get().toString()); + } + if (request.getPageToken().isPresent()) { + httpUrl.addQueryParameter("page_token", request.getPageToken().get()); + } + if (request.getOrderBy().isPresent()) { + httpUrl.addQueryParameter("order_by", request.getOrderBy().get()); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListFinetunedModelsResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Creates a new fine-tuned model. The model will be trained on the dataset specified in the request body. The training process may take some time, and the model will be available once the training is complete. */ public CreateFinetunedModelResponse createFinetunedModel(FinetunedModel request) { - return this.rawClient.createFinetunedModel(request).body(); + return createFinetunedModel(request, null); } /** * Creates a new fine-tuned model. The model will be trained on the dataset specified in the request body. The training process may take some time, and the model will be available once the training is complete. */ public CreateFinetunedModelResponse createFinetunedModel(FinetunedModel request, RequestOptions requestOptions) { - return this.rawClient.createFinetunedModel(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/finetuning/finetuned-models") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateFinetunedModelResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Retrieve a fine-tuned model by its ID. */ public GetFinetunedModelResponse getFinetunedModel(String id) { - return this.rawClient.getFinetunedModel(id).body(); + return getFinetunedModel(id, null); } /** * Retrieve a fine-tuned model by its ID. */ public GetFinetunedModelResponse getFinetunedModel(String id, RequestOptions requestOptions) { - return this.rawClient.getFinetunedModel(id, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/finetuning/finetuned-models") + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetFinetunedModelResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -90,7 +261,7 @@ public GetFinetunedModelResponse getFinetunedModel(String id, RequestOptions req * This operation is irreversible. */ public Map deleteFinetunedModel(String id) { - return this.rawClient.deleteFinetunedModel(id).body(); + return deleteFinetunedModel(id, null); } /** @@ -98,14 +269,64 @@ public Map deleteFinetunedModel(String id) { * This operation is irreversible. */ public Map deleteFinetunedModel(String id, RequestOptions requestOptions) { - return this.rawClient.deleteFinetunedModel(id, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/finetuning/finetuned-models") + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), new TypeReference>() {}); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Updates the fine-tuned model with the given ID. The model will be updated with the new settings and name provided in the request body. */ public UpdateFinetunedModelResponse updateFinetunedModel(String id, FinetuningUpdateFinetunedModelRequest request) { - return this.rawClient.updateFinetunedModel(id, request).body(); + return updateFinetunedModel(id, request, null); } /** @@ -113,7 +334,63 @@ public UpdateFinetunedModelResponse updateFinetunedModel(String id, FinetuningUp */ public UpdateFinetunedModelResponse updateFinetunedModel( String id, FinetuningUpdateFinetunedModelRequest request, RequestOptions requestOptions) { - return this.rawClient.updateFinetunedModel(id, request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/finetuning/finetuned-models") + .addPathSegment(id) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PATCH", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UpdateFinetunedModelResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -122,7 +399,8 @@ public UpdateFinetunedModelResponse updateFinetunedModel( * The list can be paginated using page_size and page_token parameters. */ public ListEventsResponse listEvents(String finetunedModelId) { - return this.rawClient.listEvents(finetunedModelId).body(); + return listEvents( + finetunedModelId, FinetuningListEventsRequest.builder().build()); } /** @@ -131,7 +409,7 @@ public ListEventsResponse listEvents(String finetunedModelId) { * The list can be paginated using page_size and page_token parameters. */ public ListEventsResponse listEvents(String finetunedModelId, FinetuningListEventsRequest request) { - return this.rawClient.listEvents(finetunedModelId, request).body(); + return listEvents(finetunedModelId, request, null); } /** @@ -141,9 +419,65 @@ public ListEventsResponse listEvents(String finetunedModelId, FinetuningListEven */ public ListEventsResponse listEvents( String finetunedModelId, FinetuningListEventsRequest request, RequestOptions requestOptions) { - return this.rawClient - .listEvents(finetunedModelId, request, requestOptions) - .body(); + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/finetuning/finetuned-models") + .addPathSegment(finetunedModelId) + .addPathSegments("events"); + if (request.getPageSize().isPresent()) { + httpUrl.addQueryParameter("page_size", request.getPageSize().get().toString()); + } + if (request.getPageToken().isPresent()) { + httpUrl.addQueryParameter("page_token", request.getPageToken().get()); + } + if (request.getOrderBy().isPresent()) { + httpUrl.addQueryParameter("order_by", request.getOrderBy().get()); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEventsResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -152,7 +486,9 @@ public ListEventsResponse listEvents( * The list can be paginated using page_size and page_token parameters. */ public ListTrainingStepMetricsResponse listTrainingStepMetrics(String finetunedModelId) { - return this.rawClient.listTrainingStepMetrics(finetunedModelId).body(); + return listTrainingStepMetrics( + finetunedModelId, + FinetuningListTrainingStepMetricsRequest.builder().build()); } /** @@ -162,7 +498,7 @@ public ListTrainingStepMetricsResponse listTrainingStepMetrics(String finetunedM */ public ListTrainingStepMetricsResponse listTrainingStepMetrics( String finetunedModelId, FinetuningListTrainingStepMetricsRequest request) { - return this.rawClient.listTrainingStepMetrics(finetunedModelId, request).body(); + return listTrainingStepMetrics(finetunedModelId, request, null); } /** @@ -172,8 +508,62 @@ public ListTrainingStepMetricsResponse listTrainingStepMetrics( */ public ListTrainingStepMetricsResponse listTrainingStepMetrics( String finetunedModelId, FinetuningListTrainingStepMetricsRequest request, RequestOptions requestOptions) { - return this.rawClient - .listTrainingStepMetrics(finetunedModelId, request, requestOptions) - .body(); + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/finetuning/finetuned-models") + .addPathSegment(finetunedModelId) + .addPathSegments("training-step-metrics"); + if (request.getPageSize().isPresent()) { + httpUrl.addQueryParameter("page_size", request.getPageSize().get().toString()); + } + if (request.getPageToken().isPresent()) { + httpUrl.addQueryParameter("page_token", request.getPageToken().get()); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), ListTrainingStepMetricsResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw 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 deleted file mode 100644 index 1dd95fc..0000000 --- a/src/main/java/com/cohere/api/resources/finetuning/RawFinetuningClient.java +++ /dev/null @@ -1,619 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.finetuning; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.QueryStringMapper; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.resources.finetuning.finetuning.types.CreateFinetunedModelResponse; -import com.cohere.api.resources.finetuning.finetuning.types.FinetunedModel; -import com.cohere.api.resources.finetuning.finetuning.types.GetFinetunedModelResponse; -import com.cohere.api.resources.finetuning.finetuning.types.ListEventsResponse; -import com.cohere.api.resources.finetuning.finetuning.types.ListFinetunedModelsResponse; -import com.cohere.api.resources.finetuning.finetuning.types.ListTrainingStepMetricsResponse; -import com.cohere.api.resources.finetuning.finetuning.types.UpdateFinetunedModelResponse; -import com.cohere.api.resources.finetuning.requests.FinetuningListEventsRequest; -import com.cohere.api.resources.finetuning.requests.FinetuningListFinetunedModelsRequest; -import com.cohere.api.resources.finetuning.requests.FinetuningListTrainingStepMetricsRequest; -import com.cohere.api.resources.finetuning.requests.FinetuningUpdateFinetunedModelRequest; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import java.io.IOException; -import java.util.Map; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; - -public class RawFinetuningClient { - protected final ClientOptions clientOptions; - - public RawFinetuningClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Returns a list of fine-tuned models that the user has access to. - */ - public CohereHttpResponse listFinetunedModels() { - return listFinetunedModels( - FinetuningListFinetunedModelsRequest.builder().build()); - } - - /** - * Returns a list of fine-tuned models that the user has access to. - */ - public CohereHttpResponse listFinetunedModels( - FinetuningListFinetunedModelsRequest request) { - return listFinetunedModels(request, null); - } - - /** - * Returns a list of fine-tuned models that the user has access to. - */ - public CohereHttpResponse listFinetunedModels( - FinetuningListFinetunedModelsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models"); - if (request.getPageSize().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_size", request.getPageSize().get(), false); - } - if (request.getPageToken().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_token", request.getPageToken().get(), false); - } - if (request.getOrderBy().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "order_by", request.getOrderBy().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListFinetunedModelsResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Creates a new fine-tuned model. The model will be trained on the dataset specified in the request body. The training process may take some time, and the model will be available once the training is complete. - */ - public CohereHttpResponse createFinetunedModel(FinetunedModel request) { - return createFinetunedModel(request, null); - } - - /** - * Creates a new fine-tuned model. The model will be trained on the dataset specified in the request body. The training process may take some time, and the model will be available once the training is complete. - */ - public CohereHttpResponse createFinetunedModel( - FinetunedModel request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateFinetunedModelResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Retrieve a fine-tuned model by its ID. - */ - public CohereHttpResponse getFinetunedModel(String id) { - return getFinetunedModel(id, null); - } - - /** - * Retrieve a fine-tuned model by its ID. - */ - public CohereHttpResponse getFinetunedModel(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetFinetunedModelResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Deletes a fine-tuned model. The model will be removed from the system and will no longer be available for use. - * This operation is irreversible. - */ - public CohereHttpResponse> deleteFinetunedModel(String id) { - return deleteFinetunedModel(id, null); - } - - /** - * Deletes a fine-tuned model. The model will be removed from the system and will no longer be available for use. - * This operation is irreversible. - */ - public CohereHttpResponse> deleteFinetunedModel(String id, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(id) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("DELETE", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Updates the fine-tuned model with the given ID. The model will be updated with the new settings and name provided in the request body. - */ - public CohereHttpResponse updateFinetunedModel( - String id, FinetuningUpdateFinetunedModelRequest request) { - return updateFinetunedModel(id, request, null); - } - - /** - * Updates the fine-tuned model with the given ID. The model will be updated with the new settings and name provided in the request body. - */ - public CohereHttpResponse updateFinetunedModel( - String id, FinetuningUpdateFinetunedModelRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(id) - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("PATCH", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UpdateFinetunedModelResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Returns a list of events that occurred during the life-cycle of the fine-tuned model. - * The events are ordered by creation time, with the most recent event first. - * The list can be paginated using page_size and page_token parameters. - */ - public CohereHttpResponse listEvents(String finetunedModelId) { - return listEvents( - finetunedModelId, FinetuningListEventsRequest.builder().build()); - } - - /** - * Returns a list of events that occurred during the life-cycle of the fine-tuned model. - * The events are ordered by creation time, with the most recent event first. - * The list can be paginated using page_size and page_token parameters. - */ - public CohereHttpResponse listEvents( - String finetunedModelId, FinetuningListEventsRequest request) { - return listEvents(finetunedModelId, request, null); - } - - /** - * Returns a list of events that occurred during the life-cycle of the fine-tuned model. - * The events are ordered by creation time, with the most recent event first. - * The list can be paginated using page_size and page_token parameters. - */ - public CohereHttpResponse listEvents( - String finetunedModelId, FinetuningListEventsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(finetunedModelId) - .addPathSegments("events"); - if (request.getPageSize().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_size", request.getPageSize().get(), false); - } - if (request.getPageToken().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_token", request.getPageToken().get(), false); - } - if (request.getOrderBy().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "order_by", request.getOrderBy().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEventsResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Returns a list of metrics measured during the training of a fine-tuned model. - * The metrics are ordered by step number, with the most recent step first. - * The list can be paginated using page_size and page_token parameters. - */ - public CohereHttpResponse listTrainingStepMetrics(String finetunedModelId) { - return listTrainingStepMetrics( - finetunedModelId, - FinetuningListTrainingStepMetricsRequest.builder().build()); - } - - /** - * Returns a list of metrics measured during the training of a fine-tuned model. - * The metrics are ordered by step number, with the most recent step first. - * The list can be paginated using page_size and page_token parameters. - */ - public CohereHttpResponse listTrainingStepMetrics( - String finetunedModelId, FinetuningListTrainingStepMetricsRequest request) { - return listTrainingStepMetrics(finetunedModelId, request, null); - } - - /** - * Returns a list of metrics measured during the training of a fine-tuned model. - * The metrics are ordered by step number, with the most recent step first. - * The list can be paginated using page_size and page_token parameters. - */ - public CohereHttpResponse listTrainingStepMetrics( - String finetunedModelId, FinetuningListTrainingStepMetricsRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/finetuning/finetuned-models") - .addPathSegment(finetunedModelId) - .addPathSegments("training-step-metrics"); - if (request.getPageSize().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_size", request.getPageSize().get(), false); - } - if (request.getPageToken().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_token", request.getPageToken().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ListTrainingStepMetricsResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - 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/BaseModel.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/BaseModel.java index b16a549..c214490 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/BaseModel.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/BaseModel.java @@ -109,9 +109,6 @@ public static BaseTypeStage builder() { } public interface BaseTypeStage { - /** - *

    The type of the base model.

    - */ _FinalStage baseType(@NotNull BaseType baseType); Builder from(BaseModel other); @@ -120,23 +117,14 @@ public interface BaseTypeStage { public interface _FinalStage { BaseModel build(); - /** - *

    The name of the base model.

    - */ _FinalStage name(Optional name); _FinalStage name(String name); - /** - *

    read-only. The version of the base model.

    - */ _FinalStage version(Optional version); _FinalStage version(String version); - /** - *

    Deprecated: The fine-tuning strategy.

    - */ _FinalStage strategy(Optional strategy); _FinalStage strategy(Strategy strategy); @@ -167,7 +155,6 @@ public Builder from(BaseModel other) { } /** - *

    The type of the base model.

    *

    The type of the base model.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -188,9 +175,6 @@ public _FinalStage strategy(Strategy strategy) { return this; } - /** - *

    Deprecated: The fine-tuning strategy.

    - */ @java.lang.Override @JsonSetter(value = "strategy", nulls = Nulls.SKIP) public _FinalStage strategy(Optional strategy) { @@ -208,9 +192,6 @@ public _FinalStage version(String version) { return this; } - /** - *

    read-only. The version of the base model.

    - */ @java.lang.Override @JsonSetter(value = "version", nulls = Nulls.SKIP) public _FinalStage version(Optional version) { @@ -228,9 +209,6 @@ public _FinalStage name(String name) { return this; } - /** - *

    The name of the base model.

    - */ @java.lang.Override @JsonSetter(value = "name", nulls = Nulls.SKIP) public _FinalStage name(Optional name) { diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/CreateFinetunedModelResponse.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/CreateFinetunedModelResponse.java index 20828cc..4f0b8ba 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/CreateFinetunedModelResponse.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/CreateFinetunedModelResponse.java @@ -81,9 +81,6 @@ public Builder from(CreateFinetunedModelResponse other) { return this; } - /** - *

    Information about the fine-tuned model.

    - */ @JsonSetter(value = "finetuned_model", nulls = Nulls.SKIP) public Builder finetunedModel(Optional finetunedModel) { this.finetunedModel = finetunedModel; diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Event.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Event.java index 948523a..72c1d44 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Event.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Event.java @@ -113,9 +113,6 @@ public Builder from(Event other) { return this; } - /** - *

    ID of the user who initiated the event. Empty if initiated by the system.

    - */ @JsonSetter(value = "user_id", nulls = Nulls.SKIP) public Builder userId(Optional userId) { this.userId = userId; @@ -127,9 +124,6 @@ public Builder userId(String userId) { return this; } - /** - *

    Status of the fine-tuned model.

    - */ @JsonSetter(value = "status", nulls = Nulls.SKIP) public Builder status(Optional status) { this.status = status; @@ -141,9 +135,6 @@ public Builder status(Status status) { return this; } - /** - *

    Timestamp when the event happened.

    - */ @JsonSetter(value = "created_at", nulls = Nulls.SKIP) public Builder createdAt(Optional createdAt) { this.createdAt = createdAt; diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/FinetunedModel.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/FinetunedModel.java index d7a38b3..2525123 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/FinetunedModel.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/FinetunedModel.java @@ -198,76 +198,46 @@ public static NameStage builder() { } public interface NameStage { - /** - *

    FinetunedModel name (e.g. foobar).

    - */ SettingsStage name(@NotNull String name); Builder from(FinetunedModel other); } public interface SettingsStage { - /** - *

    FinetunedModel settings such as dataset, hyperparameters...

    - */ _FinalStage settings(@NotNull Settings settings); } public interface _FinalStage { FinetunedModel build(); - /** - *

    read-only. FinetunedModel ID.

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

    read-only. User ID of the creator.

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

    read-only. Organization ID.

    - */ _FinalStage organizationId(Optional organizationId); _FinalStage organizationId(String organizationId); - /** - *

    read-only. Current stage in the life-cycle of the fine-tuned model.

    - */ _FinalStage status(Optional status); _FinalStage status(Status status); - /** - *

    read-only. Creation timestamp.

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

    read-only. Latest update timestamp.

    - */ _FinalStage updatedAt(Optional updatedAt); _FinalStage updatedAt(OffsetDateTime updatedAt); - /** - *

    read-only. Timestamp for the completed fine-tuning.

    - */ _FinalStage completedAt(Optional completedAt); _FinalStage completedAt(OffsetDateTime completedAt); - /** - *

    read-only. Deprecated: Timestamp for the latest request to this fine-tuned model.

    - */ _FinalStage lastUsed(Optional lastUsed); _FinalStage lastUsed(OffsetDateTime lastUsed); @@ -316,7 +286,6 @@ public Builder from(FinetunedModel other) { } /** - *

    FinetunedModel name (e.g. foobar).

    *

    FinetunedModel name (e.g. foobar).

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -328,7 +297,6 @@ public SettingsStage name(@NotNull String name) { } /** - *

    FinetunedModel settings such as dataset, hyperparameters...

    *

    FinetunedModel settings such as dataset, hyperparameters...

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -349,9 +317,6 @@ public _FinalStage lastUsed(OffsetDateTime lastUsed) { return this; } - /** - *

    read-only. Deprecated: Timestamp for the latest request to this fine-tuned model.

    - */ @java.lang.Override @JsonSetter(value = "last_used", nulls = Nulls.SKIP) public _FinalStage lastUsed(Optional lastUsed) { @@ -369,9 +334,6 @@ public _FinalStage completedAt(OffsetDateTime completedAt) { return this; } - /** - *

    read-only. Timestamp for the completed fine-tuning.

    - */ @java.lang.Override @JsonSetter(value = "completed_at", nulls = Nulls.SKIP) public _FinalStage completedAt(Optional completedAt) { @@ -389,9 +351,6 @@ public _FinalStage updatedAt(OffsetDateTime updatedAt) { return this; } - /** - *

    read-only. Latest update timestamp.

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

    read-only. Creation timestamp.

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

    read-only. Current stage in the life-cycle of the fine-tuned model.

    - */ @java.lang.Override @JsonSetter(value = "status", nulls = Nulls.SKIP) public _FinalStage status(Optional status) { @@ -449,9 +402,6 @@ public _FinalStage organizationId(String organizationId) { return this; } - /** - *

    read-only. Organization ID.

    - */ @java.lang.Override @JsonSetter(value = "organization_id", nulls = Nulls.SKIP) public _FinalStage organizationId(Optional organizationId) { @@ -469,9 +419,6 @@ public _FinalStage creatorId(String creatorId) { return this; } - /** - *

    read-only. User ID of the creator.

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

    read-only. FinetunedModel ID.

    - */ @java.lang.Override @JsonSetter(value = "id", nulls = Nulls.SKIP) public _FinalStage id(Optional id) { diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/GetFinetunedModelResponse.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/GetFinetunedModelResponse.java index 50e38c1..ec9c5ee 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/GetFinetunedModelResponse.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/GetFinetunedModelResponse.java @@ -81,9 +81,6 @@ public Builder from(GetFinetunedModelResponse other) { return this; } - /** - *

    Information about the fine-tuned model.

    - */ @JsonSetter(value = "finetuned_model", nulls = Nulls.SKIP) public Builder finetunedModel(Optional finetunedModel) { this.finetunedModel = finetunedModel; diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Hyperparameters.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Hyperparameters.java index 8099e96..5a45709 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Hyperparameters.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Hyperparameters.java @@ -206,10 +206,6 @@ public Builder from(Hyperparameters other) { return this; } - /** - *

    Stops training if the loss metric does not improve beyond the value of - * early_stopping_threshold after this many times of evaluation.

    - */ @JsonSetter(value = "early_stopping_patience", nulls = Nulls.SKIP) public Builder earlyStoppingPatience(Optional earlyStoppingPatience) { this.earlyStoppingPatience = earlyStoppingPatience; @@ -221,9 +217,6 @@ public Builder earlyStoppingPatience(Integer earlyStoppingPatience) { return this; } - /** - *

    How much the loss must improve to prevent early stopping.

    - */ @JsonSetter(value = "early_stopping_threshold", nulls = Nulls.SKIP) public Builder earlyStoppingThreshold(Optional earlyStoppingThreshold) { this.earlyStoppingThreshold = earlyStoppingThreshold; @@ -235,10 +228,6 @@ public Builder earlyStoppingThreshold(Double earlyStoppingThreshold) { return this; } - /** - *

    The batch size is the number of training examples included in a single - * training pass.

    - */ @JsonSetter(value = "train_batch_size", nulls = Nulls.SKIP) public Builder trainBatchSize(Optional trainBatchSize) { this.trainBatchSize = trainBatchSize; @@ -250,9 +239,6 @@ public Builder trainBatchSize(Integer trainBatchSize) { return this; } - /** - *

    The number of epochs to train for.

    - */ @JsonSetter(value = "train_epochs", nulls = Nulls.SKIP) public Builder trainEpochs(Optional trainEpochs) { this.trainEpochs = trainEpochs; @@ -264,9 +250,6 @@ public Builder trainEpochs(Integer trainEpochs) { return this; } - /** - *

    The learning rate to be used during training.

    - */ @JsonSetter(value = "learning_rate", nulls = Nulls.SKIP) public Builder learningRate(Optional learningRate) { this.learningRate = learningRate; @@ -278,10 +261,6 @@ public Builder learningRate(Double learningRate) { return this; } - /** - *

    Controls the scaling factor for LoRA updates. Higher values make the - * updates more impactful.

    - */ @JsonSetter(value = "lora_alpha", nulls = Nulls.SKIP) public Builder loraAlpha(Optional loraAlpha) { this.loraAlpha = loraAlpha; @@ -293,10 +272,6 @@ public Builder loraAlpha(Integer loraAlpha) { return this; } - /** - *

    Specifies the rank for low-rank matrices. Lower ranks reduce parameters - * but may limit model flexibility.

    - */ @JsonSetter(value = "lora_rank", nulls = Nulls.SKIP) public Builder loraRank(Optional loraRank) { this.loraRank = loraRank; @@ -308,9 +283,6 @@ public Builder loraRank(Integer loraRank) { return this; } - /** - *

    The combination of LoRA modules to target.

    - */ @JsonSetter(value = "lora_target_modules", nulls = Nulls.SKIP) public Builder loraTargetModules(Optional loraTargetModules) { this.loraTargetModules = loraTargetModules; diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListEventsResponse.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListEventsResponse.java index 473fa3f..9f9fb33 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListEventsResponse.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListEventsResponse.java @@ -116,9 +116,6 @@ public Builder from(ListEventsResponse other) { return this; } - /** - *

    List of events for the fine-tuned model.

    - */ @JsonSetter(value = "events", nulls = Nulls.SKIP) public Builder events(Optional> events) { this.events = events; @@ -130,10 +127,6 @@ public Builder events(List events) { return this; } - /** - *

    Pagination token to retrieve the next page of results. If the value is "", - * it means no further results for the request.

    - */ @JsonSetter(value = "next_page_token", nulls = Nulls.SKIP) public Builder nextPageToken(Optional nextPageToken) { this.nextPageToken = nextPageToken; @@ -145,9 +138,6 @@ public Builder nextPageToken(String nextPageToken) { return this; } - /** - *

    Total count of results.

    - */ @JsonSetter(value = "total_size", nulls = Nulls.SKIP) public Builder totalSize(Optional totalSize) { this.totalSize = totalSize; diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListFinetunedModelsResponse.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListFinetunedModelsResponse.java index 71c1484..561f649 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListFinetunedModelsResponse.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListFinetunedModelsResponse.java @@ -116,9 +116,6 @@ public Builder from(ListFinetunedModelsResponse other) { return this; } - /** - *

    List of fine-tuned models matching the request.

    - */ @JsonSetter(value = "finetuned_models", nulls = Nulls.SKIP) public Builder finetunedModels(Optional> finetunedModels) { this.finetunedModels = finetunedModels; @@ -130,10 +127,6 @@ public Builder finetunedModels(List finetunedModels) { return this; } - /** - *

    Pagination token to retrieve the next page of results. If the value is "", - * it means no further results for the request.

    - */ @JsonSetter(value = "next_page_token", nulls = Nulls.SKIP) public Builder nextPageToken(Optional nextPageToken) { this.nextPageToken = nextPageToken; @@ -145,9 +138,6 @@ public Builder nextPageToken(String nextPageToken) { return this; } - /** - *

    Total count of results.

    - */ @JsonSetter(value = "total_size", nulls = Nulls.SKIP) public Builder totalSize(Optional totalSize) { this.totalSize = totalSize; diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListTrainingStepMetricsResponse.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListTrainingStepMetricsResponse.java index 4cedc0e..14d4d58 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListTrainingStepMetricsResponse.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/ListTrainingStepMetricsResponse.java @@ -99,9 +99,6 @@ public Builder from(ListTrainingStepMetricsResponse other) { return this; } - /** - *

    The metrics for each step the evaluation was run on.

    - */ @JsonSetter(value = "step_metrics", nulls = Nulls.SKIP) public Builder stepMetrics(Optional> stepMetrics) { this.stepMetrics = stepMetrics; @@ -113,10 +110,6 @@ public Builder stepMetrics(List stepMetrics) { return this; } - /** - *

    Pagination token to retrieve the next page of results. If the value is "", - * it means no further results for the request.

    - */ @JsonSetter(value = "next_page_token", nulls = Nulls.SKIP) public Builder nextPageToken(Optional nextPageToken) { this.nextPageToken = nextPageToken; diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Settings.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Settings.java index 30eaef2..6930af7 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Settings.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Settings.java @@ -122,41 +122,26 @@ public static BaseModelStage builder() { } public interface BaseModelStage { - /** - *

    The base model to fine-tune.

    - */ DatasetIdStage baseModel(@NotNull BaseModel baseModel); Builder from(Settings other); } public interface DatasetIdStage { - /** - *

    The data used for training and evaluating the fine-tuned model.

    - */ _FinalStage datasetId(@NotNull String datasetId); } public interface _FinalStage { Settings build(); - /** - *

    Fine-tuning hyper-parameters.

    - */ _FinalStage hyperparameters(Optional hyperparameters); _FinalStage hyperparameters(Hyperparameters hyperparameters); - /** - *

    read-only. Whether the model is single-label or multi-label (only for classification).

    - */ _FinalStage multiLabel(Optional multiLabel); _FinalStage multiLabel(Boolean multiLabel); - /** - *

    The Weights & Biases configuration (Chat fine-tuning only).

    - */ _FinalStage wandb(Optional wandb); _FinalStage wandb(WandbConfig wandb); @@ -190,7 +175,6 @@ public Builder from(Settings other) { } /** - *

    The base model to fine-tune.

    *

    The base model to fine-tune.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -202,7 +186,6 @@ public DatasetIdStage baseModel(@NotNull BaseModel baseModel) { } /** - *

    The data used for training and evaluating the fine-tuned model.

    *

    The data used for training and evaluating the fine-tuned model.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -223,9 +206,6 @@ public _FinalStage wandb(WandbConfig wandb) { return this; } - /** - *

    The Weights & Biases configuration (Chat fine-tuning only).

    - */ @java.lang.Override @JsonSetter(value = "wandb", nulls = Nulls.SKIP) public _FinalStage wandb(Optional wandb) { @@ -243,9 +223,6 @@ public _FinalStage multiLabel(Boolean multiLabel) { return this; } - /** - *

    read-only. Whether the model is single-label or multi-label (only for classification).

    - */ @java.lang.Override @JsonSetter(value = "multi_label", nulls = Nulls.SKIP) public _FinalStage multiLabel(Optional multiLabel) { @@ -263,9 +240,6 @@ public _FinalStage hyperparameters(Hyperparameters hyperparameters) { return this; } - /** - *

    Fine-tuning hyper-parameters.

    - */ @java.lang.Override @JsonSetter(value = "hyperparameters", nulls = Nulls.SKIP) public _FinalStage hyperparameters(Optional hyperparameters) { diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/TrainingStepMetrics.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/TrainingStepMetrics.java index 38088f5..60e4c1b 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/TrainingStepMetrics.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/TrainingStepMetrics.java @@ -115,9 +115,6 @@ public Builder from(TrainingStepMetrics other) { return this; } - /** - *

    Creation timestamp.

    - */ @JsonSetter(value = "created_at", nulls = Nulls.SKIP) public Builder createdAt(Optional createdAt) { this.createdAt = createdAt; @@ -129,9 +126,6 @@ public Builder createdAt(OffsetDateTime createdAt) { return this; } - /** - *

    Step number.

    - */ @JsonSetter(value = "step_number", nulls = Nulls.SKIP) public Builder stepNumber(Optional stepNumber) { this.stepNumber = stepNumber; @@ -143,9 +137,6 @@ public Builder stepNumber(Integer stepNumber) { return this; } - /** - *

    Map of names and values for each evaluation metrics.

    - */ @JsonSetter(value = "metrics", nulls = Nulls.SKIP) public Builder metrics(Optional> metrics) { this.metrics = metrics; diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/UpdateFinetunedModelResponse.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/UpdateFinetunedModelResponse.java index 8cd25f5..0d6aa84 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/UpdateFinetunedModelResponse.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/UpdateFinetunedModelResponse.java @@ -81,9 +81,6 @@ public Builder from(UpdateFinetunedModelResponse other) { return this; } - /** - *

    Information about the fine-tuned model.

    - */ @JsonSetter(value = "finetuned_model", nulls = Nulls.SKIP) public Builder finetunedModel(Optional finetunedModel) { this.finetunedModel = finetunedModel; diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/WandbConfig.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/WandbConfig.java index 886c098..661db80 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/WandbConfig.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/WandbConfig.java @@ -91,27 +91,18 @@ public static ProjectStage builder() { } public interface ProjectStage { - /** - *

    The WandB project name to be used during training.

    - */ ApiKeyStage project(@NotNull String project); Builder from(WandbConfig other); } public interface ApiKeyStage { - /** - *

    The WandB API key to be used during training.

    - */ _FinalStage apiKey(@NotNull String apiKey); } public interface _FinalStage { WandbConfig build(); - /** - *

    The WandB entity name to be used during training.

    - */ _FinalStage entity(Optional entity); _FinalStage entity(String entity); @@ -139,7 +130,6 @@ public Builder from(WandbConfig other) { } /** - *

    The WandB project name to be used during training.

    *

    The WandB project name to be used during training.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -151,7 +141,6 @@ public ApiKeyStage project(@NotNull String project) { } /** - *

    The WandB API key to be used during training.

    *

    The WandB API key to be used during training.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -172,9 +161,6 @@ public _FinalStage entity(String entity) { return this; } - /** - *

    The WandB entity name to be used during training.

    - */ @java.lang.Override @JsonSetter(value = "entity", nulls = Nulls.SKIP) public _FinalStage entity(Optional entity) { diff --git a/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListEventsRequest.java b/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListEventsRequest.java index de066fc..2c52f2c 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListEventsRequest.java +++ b/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListEventsRequest.java @@ -119,10 +119,6 @@ public Builder from(FinetuningListEventsRequest other) { return this; } - /** - *

    Maximum number of results to be returned by the server. If 0, defaults to - * 50.

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

    Request a specific page of the list results.

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

    Comma separated list of fields. For example: "created_at,name". The default - * sorting order is ascending. To specify descending order for a field, append - * " desc" to the field name. For example: "created_at desc,name".

    - *

    Supported sorting fields:

    - *
      - *
    • created_at (default)
    • - *
    - */ @JsonSetter(value = "order_by", nulls = Nulls.SKIP) public Builder orderBy(Optional orderBy) { this.orderBy = orderBy; diff --git a/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListFinetunedModelsRequest.java b/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListFinetunedModelsRequest.java index 5c3149f..af0e5f8 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListFinetunedModelsRequest.java +++ b/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListFinetunedModelsRequest.java @@ -120,10 +120,6 @@ public Builder from(FinetuningListFinetunedModelsRequest other) { return this; } - /** - *

    Maximum number of results to be returned by the server. If 0, defaults to - * 50.

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

    Request a specific page of the list results.

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

    Comma separated list of fields. For example: "created_at,name". The default - * sorting order is ascending. To specify descending order for a field, append - * " desc" to the field name. For example: "created_at desc,name".

    - *

    Supported sorting fields:

    - *
      - *
    • created_at (default)
    • - *
    - */ @JsonSetter(value = "order_by", nulls = Nulls.SKIP) public Builder orderBy(Optional orderBy) { this.orderBy = orderBy; diff --git a/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListTrainingStepMetricsRequest.java b/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListTrainingStepMetricsRequest.java index 7c61265..c2a7659 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListTrainingStepMetricsRequest.java +++ b/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningListTrainingStepMetricsRequest.java @@ -97,10 +97,6 @@ public Builder from(FinetuningListTrainingStepMetricsRequest other) { return this; } - /** - *

    Maximum number of results to be returned by the server. If 0, defaults to - * 50.

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

    Request a specific page of the list results.

    - */ @JsonSetter(value = "page_token", nulls = Nulls.SKIP) public Builder pageToken(Optional pageToken) { this.pageToken = pageToken; diff --git a/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningUpdateFinetunedModelRequest.java b/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningUpdateFinetunedModelRequest.java index 78a0e70..2fe5ea0 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningUpdateFinetunedModelRequest.java +++ b/src/main/java/com/cohere/api/resources/finetuning/requests/FinetuningUpdateFinetunedModelRequest.java @@ -14,6 +14,7 @@ import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.time.OffsetDateTime; import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -25,17 +26,44 @@ public final class FinetuningUpdateFinetunedModelRequest { private final String name; + private final Optional creatorId; + + private final Optional organizationId; + private final Settings settings; private final Optional status; + private final Optional createdAt; + + private final Optional updatedAt; + + private final Optional completedAt; + + private final Optional lastUsed; + private final Map additionalProperties; private FinetuningUpdateFinetunedModelRequest( - String name, Settings settings, Optional status, Map additionalProperties) { + String name, + Optional creatorId, + Optional organizationId, + Settings settings, + Optional status, + Optional createdAt, + Optional updatedAt, + Optional completedAt, + Optional lastUsed, + Map additionalProperties) { this.name = name; + this.creatorId = creatorId; + this.organizationId = organizationId; this.settings = settings; this.status = status; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.completedAt = completedAt; + this.lastUsed = lastUsed; this.additionalProperties = additionalProperties; } @@ -47,6 +75,22 @@ public String getName() { return name; } + /** + * @return User ID of the creator. + */ + @JsonProperty("creator_id") + public Optional getCreatorId() { + return creatorId; + } + + /** + * @return Organization ID. + */ + @JsonProperty("organization_id") + public Optional getOrganizationId() { + return organizationId; + } + /** * @return FinetunedModel settings such as dataset, hyperparameters... */ @@ -63,6 +107,38 @@ public Optional getStatus() { return status; } + /** + * @return Creation timestamp. + */ + @JsonProperty("created_at") + public Optional getCreatedAt() { + return createdAt; + } + + /** + * @return Latest update timestamp. + */ + @JsonProperty("updated_at") + public Optional getUpdatedAt() { + return updatedAt; + } + + /** + * @return Timestamp for the completed fine-tuning. + */ + @JsonProperty("completed_at") + public Optional getCompletedAt() { + return completedAt; + } + + /** + * @return Deprecated: Timestamp for the latest request to this fine-tuned model. + */ + @JsonProperty("last_used") + public Optional getLastUsed() { + return lastUsed; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -76,12 +152,29 @@ public Map getAdditionalProperties() { } private boolean equalTo(FinetuningUpdateFinetunedModelRequest other) { - return name.equals(other.name) && settings.equals(other.settings) && status.equals(other.status); + return name.equals(other.name) + && creatorId.equals(other.creatorId) + && organizationId.equals(other.organizationId) + && settings.equals(other.settings) + && status.equals(other.status) + && createdAt.equals(other.createdAt) + && updatedAt.equals(other.updatedAt) + && completedAt.equals(other.completedAt) + && lastUsed.equals(other.lastUsed); } @java.lang.Override public int hashCode() { - return Objects.hash(this.name, this.settings, this.status); + return Objects.hash( + this.name, + this.creatorId, + this.organizationId, + this.settings, + this.status, + this.createdAt, + this.updatedAt, + this.completedAt, + this.lastUsed); } @java.lang.Override @@ -94,30 +187,45 @@ public static NameStage builder() { } public interface NameStage { - /** - *

    FinetunedModel name (e.g. foobar).

    - */ SettingsStage name(@NotNull String name); Builder from(FinetuningUpdateFinetunedModelRequest other); } public interface SettingsStage { - /** - *

    FinetunedModel settings such as dataset, hyperparameters...

    - */ _FinalStage settings(@NotNull Settings settings); } public interface _FinalStage { FinetuningUpdateFinetunedModelRequest build(); - /** - *

    Current stage in the life-cycle of the fine-tuned model.

    - */ + _FinalStage creatorId(Optional creatorId); + + _FinalStage creatorId(String creatorId); + + _FinalStage organizationId(Optional organizationId); + + _FinalStage organizationId(String organizationId); + _FinalStage status(Optional status); _FinalStage status(Status status); + + _FinalStage createdAt(Optional createdAt); + + _FinalStage createdAt(OffsetDateTime createdAt); + + _FinalStage updatedAt(Optional updatedAt); + + _FinalStage updatedAt(OffsetDateTime updatedAt); + + _FinalStage completedAt(Optional completedAt); + + _FinalStage completedAt(OffsetDateTime completedAt); + + _FinalStage lastUsed(Optional lastUsed); + + _FinalStage lastUsed(OffsetDateTime lastUsed); } @JsonIgnoreProperties(ignoreUnknown = true) @@ -126,8 +234,20 @@ public static final class Builder implements NameStage, SettingsStage, _FinalSta private Settings settings; + private Optional lastUsed = Optional.empty(); + + private Optional completedAt = Optional.empty(); + + private Optional updatedAt = Optional.empty(); + + private Optional createdAt = Optional.empty(); + private Optional status = Optional.empty(); + private Optional organizationId = Optional.empty(); + + private Optional creatorId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -136,13 +256,18 @@ private Builder() {} @java.lang.Override public Builder from(FinetuningUpdateFinetunedModelRequest other) { name(other.getName()); + creatorId(other.getCreatorId()); + organizationId(other.getOrganizationId()); settings(other.getSettings()); status(other.getStatus()); + createdAt(other.getCreatedAt()); + updatedAt(other.getUpdatedAt()); + completedAt(other.getCompletedAt()); + lastUsed(other.getLastUsed()); return this; } /** - *

    FinetunedModel name (e.g. foobar).

    *

    FinetunedModel name (e.g. foobar).

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -154,7 +279,6 @@ public SettingsStage name(@NotNull String name) { } /** - *

    FinetunedModel settings such as dataset, hyperparameters...

    *

    FinetunedModel settings such as dataset, hyperparameters...

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -166,18 +290,83 @@ public _FinalStage settings(@NotNull Settings settings) { } /** - *

    Current stage in the life-cycle of the fine-tuned model.

    + *

    Deprecated: Timestamp for the latest request to this fine-tuned model.

    * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage status(Status status) { - this.status = Optional.ofNullable(status); + public _FinalStage lastUsed(OffsetDateTime lastUsed) { + this.lastUsed = Optional.ofNullable(lastUsed); + return this; + } + + @java.lang.Override + @JsonSetter(value = "last_used", nulls = Nulls.SKIP) + public _FinalStage lastUsed(Optional lastUsed) { + this.lastUsed = lastUsed; + return this; + } + + /** + *

    Timestamp for the completed fine-tuning.

    + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage completedAt(OffsetDateTime completedAt) { + this.completedAt = Optional.ofNullable(completedAt); + return this; + } + + @java.lang.Override + @JsonSetter(value = "completed_at", nulls = Nulls.SKIP) + public _FinalStage completedAt(Optional completedAt) { + this.completedAt = completedAt; + return this; + } + + /** + *

    Latest update timestamp.

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

    Creation timestamp.

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

    Current stage in the life-cycle of the fine-tuned model.

    + * @return Reference to {@code this} so that method calls can be chained together. */ + @java.lang.Override + public _FinalStage status(Status status) { + this.status = Optional.ofNullable(status); + return this; + } + @java.lang.Override @JsonSetter(value = "status", nulls = Nulls.SKIP) public _FinalStage status(Optional status) { @@ -185,9 +374,53 @@ public _FinalStage status(Optional status) { return this; } + /** + *

    Organization ID.

    + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage organizationId(String organizationId) { + this.organizationId = Optional.ofNullable(organizationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "organization_id", nulls = Nulls.SKIP) + public _FinalStage organizationId(Optional organizationId) { + this.organizationId = organizationId; + return this; + } + + /** + *

    User ID of the creator.

    + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage creatorId(String creatorId) { + this.creatorId = Optional.ofNullable(creatorId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "creator_id", nulls = Nulls.SKIP) + public _FinalStage creatorId(Optional creatorId) { + this.creatorId = creatorId; + return this; + } + @java.lang.Override public FinetuningUpdateFinetunedModelRequest build() { - return new FinetuningUpdateFinetunedModelRequest(name, settings, status, additionalProperties); + return new FinetuningUpdateFinetunedModelRequest( + name, + creatorId, + organizationId, + settings, + status, + createdAt, + updatedAt, + completedAt, + lastUsed, + additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/resources/models/AsyncModelsClient.java b/src/main/java/com/cohere/api/resources/models/AsyncModelsClient.java deleted file mode 100644 index a5ec2e9..0000000 --- a/src/main/java/com/cohere/api/resources/models/AsyncModelsClient.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.models; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.resources.models.requests.ModelsListRequest; -import com.cohere.api.types.GetModelResponse; -import com.cohere.api.types.ListModelsResponse; -import java.util.concurrent.CompletableFuture; - -public class AsyncModelsClient { - protected final ClientOptions clientOptions; - - private final AsyncRawModelsClient rawClient; - - public AsyncModelsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawModelsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawModelsClient withRawResponse() { - return this.rawClient; - } - - /** - * Returns the details of a model, provided its name. - */ - public CompletableFuture get(String model) { - return this.rawClient.get(model).thenApply(response -> response.body()); - } - - /** - * Returns the details of a model, provided its name. - */ - public CompletableFuture get(String model, RequestOptions requestOptions) { - return this.rawClient.get(model, requestOptions).thenApply(response -> response.body()); - } - - /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. - */ - public CompletableFuture list() { - return this.rawClient.list().thenApply(response -> response.body()); - } - - /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. - */ - public CompletableFuture list(ModelsListRequest request) { - return this.rawClient.list(request).thenApply(response -> response.body()); - } - - /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. - */ - public CompletableFuture list(ModelsListRequest request, RequestOptions requestOptions) { - return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); - } -} diff --git a/src/main/java/com/cohere/api/resources/models/AsyncRawModelsClient.java b/src/main/java/com/cohere/api/resources/models/AsyncRawModelsClient.java deleted file mode 100644 index 0a3801a..0000000 --- a/src/main/java/com/cohere/api/resources/models/AsyncRawModelsClient.java +++ /dev/null @@ -1,315 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.models; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.QueryStringMapper; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.models.requests.ModelsListRequest; -import com.cohere.api.types.GetModelResponse; -import com.cohere.api.types.ListModelsResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import java.io.IOException; -import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; - -public class AsyncRawModelsClient { - protected final ClientOptions clientOptions; - - public AsyncRawModelsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Returns the details of a model, provided its name. - */ - public CompletableFuture> get(String model) { - return get(model, null); - } - - /** - * Returns the details of a model, provided its name. - */ - public CompletableFuture> get(String model, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/models") - .addPathSegment(model) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetModelResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. - */ - public CompletableFuture> list() { - return list(ModelsListRequest.builder().build()); - } - - /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. - */ - public CompletableFuture> list(ModelsListRequest request) { - return list(request, null); - } - - /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. - */ - public CompletableFuture> list( - ModelsListRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/models"); - if (request.getPageSize().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_size", request.getPageSize().get(), false); - } - if (request.getPageToken().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_token", request.getPageToken().get(), false); - } - if (request.getEndpoint().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "endpoint", request.getEndpoint().get(), false); - } - if (request.getDefaultOnly().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "default_only", request.getDefaultOnly().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListModelsResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/src/main/java/com/cohere/api/resources/models/ModelsClient.java b/src/main/java/com/cohere/api/resources/models/ModelsClient.java index b73cf49..cd73f09 100644 --- a/src/main/java/com/cohere/api/resources/models/ModelsClient.java +++ b/src/main/java/com/cohere/api/resources/models/ModelsClient.java @@ -4,60 +4,218 @@ package com.cohere.api.resources.models; import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.CohereApiException; +import com.cohere.api.core.CohereException; +import com.cohere.api.core.ObjectMappers; import com.cohere.api.core.RequestOptions; +import com.cohere.api.errors.BadRequestError; +import com.cohere.api.errors.ClientClosedRequestError; +import com.cohere.api.errors.ForbiddenError; +import com.cohere.api.errors.GatewayTimeoutError; +import com.cohere.api.errors.InternalServerError; +import com.cohere.api.errors.InvalidTokenError; +import com.cohere.api.errors.NotFoundError; +import com.cohere.api.errors.NotImplementedError; +import com.cohere.api.errors.ServiceUnavailableError; +import com.cohere.api.errors.TooManyRequestsError; +import com.cohere.api.errors.UnauthorizedError; +import com.cohere.api.errors.UnprocessableEntityError; import com.cohere.api.resources.models.requests.ModelsListRequest; import com.cohere.api.types.GetModelResponse; import com.cohere.api.types.ListModelsResponse; +import com.fasterxml.jackson.core.JsonProcessingException; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; public class ModelsClient { protected final ClientOptions clientOptions; - private final RawModelsClient rawClient; - public ModelsClient(ClientOptions clientOptions) { this.clientOptions = clientOptions; - this.rawClient = new RawModelsClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawModelsClient withRawResponse() { - return this.rawClient; } /** * Returns the details of a model, provided its name. */ public GetModelResponse get(String model) { - return this.rawClient.get(model).body(); + return get(model, null); } /** * Returns the details of a model, provided its name. */ public GetModelResponse get(String model, RequestOptions requestOptions) { - return this.rawClient.get(model, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/models") + .addPathSegment(model) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetModelResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. */ public ListModelsResponse list() { - return this.rawClient.list().body(); + return list(ModelsListRequest.builder().build()); } /** * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. */ public ListModelsResponse list(ModelsListRequest request) { - return this.rawClient.list(request).body(); + return list(request, null); } /** * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. */ public ListModelsResponse list(ModelsListRequest request, RequestOptions requestOptions) { - return this.rawClient.list(request, requestOptions).body(); + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/models"); + if (request.getPageSize().isPresent()) { + httpUrl.addQueryParameter("page_size", request.getPageSize().get().toString()); + } + if (request.getPageToken().isPresent()) { + httpUrl.addQueryParameter("page_token", request.getPageToken().get()); + } + if (request.getEndpoint().isPresent()) { + httpUrl.addQueryParameter("endpoint", request.getEndpoint().get().toString()); + } + if (request.getDefaultOnly().isPresent()) { + httpUrl.addQueryParameter( + "default_only", request.getDefaultOnly().get().toString()); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListModelsResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw 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 deleted file mode 100644 index a094ca9..0000000 --- a/src/main/java/com/cohere/api/resources/models/RawModelsClient.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.models; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.QueryStringMapper; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.models.requests.ModelsListRequest; -import com.cohere.api.types.GetModelResponse; -import com.cohere.api.types.ListModelsResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; - -public class RawModelsClient { - protected final ClientOptions clientOptions; - - public RawModelsClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Returns the details of a model, provided its name. - */ - public CohereHttpResponse get(String model) { - return get(model, null); - } - - /** - * Returns the details of a model, provided its name. - */ - public CohereHttpResponse get(String model, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/models") - .addPathSegment(model) - .build(); - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetModelResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. - */ - public CohereHttpResponse list() { - return list(ModelsListRequest.builder().build()); - } - - /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. - */ - public CohereHttpResponse list(ModelsListRequest request) { - return list(request, null); - } - - /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. - */ - public CohereHttpResponse list(ModelsListRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/models"); - if (request.getPageSize().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_size", request.getPageSize().get(), false); - } - if (request.getPageToken().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "page_token", request.getPageToken().get(), false); - } - if (request.getEndpoint().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "endpoint", request.getEndpoint().get(), false); - } - if (request.getDefaultOnly().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "default_only", request.getDefaultOnly().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListModelsResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } -} diff --git a/src/main/java/com/cohere/api/resources/models/requests/ModelsListRequest.java b/src/main/java/com/cohere/api/resources/models/requests/ModelsListRequest.java index ab822f7..1ad08c2 100644 --- a/src/main/java/com/cohere/api/resources/models/requests/ModelsListRequest.java +++ b/src/main/java/com/cohere/api/resources/models/requests/ModelsListRequest.java @@ -132,10 +132,6 @@ public Builder from(ModelsListRequest other) { return this; } - /** - *

    Maximum number of models to include in a page - * Defaults to 20, min value of 1, max value of 1000.

    - */ @JsonSetter(value = "page_size", nulls = Nulls.SKIP) public Builder pageSize(Optional pageSize) { this.pageSize = pageSize; @@ -147,9 +143,6 @@ public Builder pageSize(Double pageSize) { return this; } - /** - *

    Page token provided in the next_page_token field of a previous response.

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

    When provided, filters the list of models to only those that are compatible with the specified endpoint.

    - */ @JsonSetter(value = "endpoint", nulls = Nulls.SKIP) public Builder endpoint(Optional endpoint) { this.endpoint = endpoint; @@ -175,9 +165,6 @@ public Builder endpoint(CompatibleEndpoint endpoint) { return this; } - /** - *

    When provided, filters the list of models to only the default model to the endpoint. This parameter is only valid when endpoint is provided.

    - */ @JsonSetter(value = "default_only", nulls = Nulls.SKIP) public Builder defaultOnly(Optional defaultOnly) { this.defaultOnly = defaultOnly; diff --git a/src/main/java/com/cohere/api/resources/v2/AsyncRawV2Client.java b/src/main/java/com/cohere/api/resources/v2/AsyncRawV2Client.java deleted file mode 100644 index 0004660..0000000 --- a/src/main/java/com/cohere/api/resources/v2/AsyncRawV2Client.java +++ /dev/null @@ -1,589 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.v2; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.core.ResponseBodyReader; -import com.cohere.api.core.Stream; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.v2.requests.V2ChatRequest; -import com.cohere.api.resources.v2.requests.V2ChatStreamRequest; -import com.cohere.api.resources.v2.requests.V2EmbedRequest; -import com.cohere.api.resources.v2.requests.V2RerankRequest; -import com.cohere.api.resources.v2.types.V2ChatResponse; -import com.cohere.api.resources.v2.types.V2ChatStreamResponse; -import com.cohere.api.resources.v2.types.V2RerankResponse; -import com.cohere.api.types.EmbedByTypeResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import java.io.IOException; -import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; - -public class AsyncRawV2Client { - protected final ClientOptions clientOptions; - - public AsyncRawV2Client(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Generates a text response to a user message. To learn how to use the Chat API and RAG follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CompletableFuture>> chatStream( - V2ChatStreamRequest request) { - return chatStream(request, null); - } - - /** - * Generates a text response to a user message. To learn how to use the Chat API and RAG follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CompletableFuture>> chatStream( - V2ChatStreamRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/chat") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture>> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - Stream.fromSse(V2ChatStreamResponse.class, new ResponseBodyReader(response)), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * Generates a text response to a user message and streams it down, token by token. To learn how to use the Chat API with streaming follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CompletableFuture> chat(V2ChatRequest request) { - return chat(request, null); - } - - /** - * Generates a text response to a user message and streams it down, token by token. To learn how to use the Chat API with streaming follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CompletableFuture> chat( - V2ChatRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/chat") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V2ChatResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This endpoint returns text embeddings. An embedding is a list of floating point numbers that captures semantic information about the text that it represents. - *

    Embeddings can be used to create text classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

    - *

    If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

    - */ - public CompletableFuture> embed(V2EmbedRequest request) { - return embed(request, null); - } - - /** - * This endpoint returns text embeddings. An embedding is a list of floating point numbers that captures semantic information about the text that it represents. - *

    Embeddings can be used to create text classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

    - *

    If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

    - */ - public CompletableFuture> embed( - V2EmbedRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/embed") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedByTypeResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CompletableFuture> rerank(V2RerankRequest request) { - return rerank(request, null); - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CompletableFuture> rerank( - V2RerankRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/rerank") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V2RerankResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - future.completeExceptionally(new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 401: - future.completeExceptionally(new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 403: - future.completeExceptionally(new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 404: - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 422: - future.completeExceptionally(new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 429: - future.completeExceptionally(new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 498: - future.completeExceptionally(new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 499: - future.completeExceptionally(new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 500: - future.completeExceptionally(new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 501: - future.completeExceptionally(new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 503: - future.completeExceptionally(new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - case 504: - future.completeExceptionally(new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/src/main/java/com/cohere/api/resources/v2/AsyncV2Client.java b/src/main/java/com/cohere/api/resources/v2/AsyncV2Client.java deleted file mode 100644 index 241eefa..0000000 --- a/src/main/java/com/cohere/api/resources/v2/AsyncV2Client.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.v2; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.resources.v2.requests.V2ChatRequest; -import com.cohere.api.resources.v2.requests.V2ChatStreamRequest; -import com.cohere.api.resources.v2.requests.V2EmbedRequest; -import com.cohere.api.resources.v2.requests.V2RerankRequest; -import com.cohere.api.resources.v2.types.V2ChatResponse; -import com.cohere.api.resources.v2.types.V2ChatStreamResponse; -import com.cohere.api.resources.v2.types.V2RerankResponse; -import com.cohere.api.types.EmbedByTypeResponse; -import java.util.concurrent.CompletableFuture; - -public class AsyncV2Client { - protected final ClientOptions clientOptions; - - private final AsyncRawV2Client rawClient; - - public AsyncV2Client(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawV2Client(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawV2Client withRawResponse() { - return this.rawClient; - } - - /** - * Generates a text response to a user message. To learn how to use the Chat API and RAG follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CompletableFuture> chatStream(V2ChatStreamRequest request) { - return this.rawClient.chatStream(request).thenApply(response -> response.body()); - } - - /** - * Generates a text response to a user message. To learn how to use the Chat API and RAG follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CompletableFuture> chatStream( - V2ChatStreamRequest request, RequestOptions requestOptions) { - return this.rawClient.chatStream(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * Generates a text response to a user message and streams it down, token by token. To learn how to use the Chat API with streaming follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CompletableFuture chat(V2ChatRequest request) { - return this.rawClient.chat(request).thenApply(response -> response.body()); - } - - /** - * Generates a text response to a user message and streams it down, token by token. To learn how to use the Chat API with streaming follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CompletableFuture chat(V2ChatRequest request, RequestOptions requestOptions) { - return this.rawClient.chat(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * This endpoint returns text embeddings. An embedding is a list of floating point numbers that captures semantic information about the text that it represents. - *

    Embeddings can be used to create text classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

    - *

    If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

    - */ - public CompletableFuture embed(V2EmbedRequest request) { - return this.rawClient.embed(request).thenApply(response -> response.body()); - } - - /** - * This endpoint returns text embeddings. An embedding is a list of floating point numbers that captures semantic information about the text that it represents. - *

    Embeddings can be used to create text classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

    - *

    If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

    - */ - public CompletableFuture embed(V2EmbedRequest request, RequestOptions requestOptions) { - return this.rawClient.embed(request, requestOptions).thenApply(response -> response.body()); - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CompletableFuture rerank(V2RerankRequest request) { - return this.rawClient.rerank(request).thenApply(response -> response.body()); - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CompletableFuture rerank(V2RerankRequest request, RequestOptions requestOptions) { - return this.rawClient.rerank(request, requestOptions).thenApply(response -> response.body()); - } -} diff --git a/src/main/java/com/cohere/api/resources/v2/RawV2Client.java b/src/main/java/com/cohere/api/resources/v2/RawV2Client.java deleted file mode 100644 index 5f4d0cd..0000000 --- a/src/main/java/com/cohere/api/resources/v2/RawV2Client.java +++ /dev/null @@ -1,430 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.resources.v2; - -import com.cohere.api.core.ClientOptions; -import com.cohere.api.core.CohereApiException; -import com.cohere.api.core.CohereException; -import com.cohere.api.core.CohereHttpResponse; -import com.cohere.api.core.MediaTypes; -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.RequestOptions; -import com.cohere.api.core.ResponseBodyReader; -import com.cohere.api.core.Stream; -import com.cohere.api.errors.BadRequestError; -import com.cohere.api.errors.ClientClosedRequestError; -import com.cohere.api.errors.ForbiddenError; -import com.cohere.api.errors.GatewayTimeoutError; -import com.cohere.api.errors.InternalServerError; -import com.cohere.api.errors.InvalidTokenError; -import com.cohere.api.errors.NotFoundError; -import com.cohere.api.errors.NotImplementedError; -import com.cohere.api.errors.ServiceUnavailableError; -import com.cohere.api.errors.TooManyRequestsError; -import com.cohere.api.errors.UnauthorizedError; -import com.cohere.api.errors.UnprocessableEntityError; -import com.cohere.api.resources.v2.requests.V2ChatRequest; -import com.cohere.api.resources.v2.requests.V2ChatStreamRequest; -import com.cohere.api.resources.v2.requests.V2EmbedRequest; -import com.cohere.api.resources.v2.requests.V2RerankRequest; -import com.cohere.api.resources.v2.types.V2ChatResponse; -import com.cohere.api.resources.v2.types.V2ChatStreamResponse; -import com.cohere.api.resources.v2.types.V2RerankResponse; -import com.cohere.api.types.EmbedByTypeResponse; -import com.fasterxml.jackson.core.JsonProcessingException; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; - -public class RawV2Client { - protected final ClientOptions clientOptions; - - public RawV2Client(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * Generates a text response to a user message. To learn how to use the Chat API and RAG follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CohereHttpResponse> chatStream(V2ChatStreamRequest request) { - return chatStream(request, null); - } - - /** - * Generates a text response to a user message. To learn how to use the Chat API and RAG follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CohereHttpResponse> chatStream( - V2ChatStreamRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/chat") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try { - Response response = client.newCall(okhttpRequest).execute(); - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - Stream.fromSse(V2ChatStreamResponse.class, new ResponseBodyReader(response)), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * Generates a text response to a user message and streams it down, token by token. To learn how to use the Chat API with streaming follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CohereHttpResponse chat(V2ChatRequest request) { - return chat(request, null); - } - - /** - * Generates a text response to a user message and streams it down, token by token. To learn how to use the Chat API with streaming follow our Text Generation guides. - *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    - */ - public CohereHttpResponse chat(V2ChatRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/chat") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V2ChatResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This endpoint returns text embeddings. An embedding is a list of floating point numbers that captures semantic information about the text that it represents. - *

    Embeddings can be used to create text classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

    - *

    If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

    - */ - public CohereHttpResponse embed(V2EmbedRequest request) { - return embed(request, null); - } - - /** - * This endpoint returns text embeddings. An embedding is a list of floating point numbers that captures semantic information about the text that it represents. - *

    Embeddings can be used to create text classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.

    - *

    If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

    - */ - public CohereHttpResponse embed(V2EmbedRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/embed") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedByTypeResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CohereHttpResponse rerank(V2RerankRequest request) { - return rerank(request, null); - } - - /** - * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. - */ - public CohereHttpResponse rerank(V2RerankRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v2/rerank") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new CohereException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V2RerankResponse.class), response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - switch (response.code()) { - case 400: - throw new BadRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 401: - throw new UnauthorizedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 403: - throw new ForbiddenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 404: - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 422: - throw new UnprocessableEntityError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 429: - throw new TooManyRequestsError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 498: - throw new InvalidTokenError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 499: - throw new ClientClosedRequestError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 500: - throw new InternalServerError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 501: - throw new NotImplementedError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 503: - throw new ServiceUnavailableError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - case 504: - throw new GatewayTimeoutError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new CohereException("Network error executing HTTP request", e); - } - } -} diff --git a/src/main/java/com/cohere/api/resources/v2/V2Client.java b/src/main/java/com/cohere/api/resources/v2/V2Client.java index 615473e..7918de7 100644 --- a/src/main/java/com/cohere/api/resources/v2/V2Client.java +++ b/src/main/java/com/cohere/api/resources/v2/V2Client.java @@ -4,63 +4,228 @@ package com.cohere.api.resources.v2; import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.CohereApiException; +import com.cohere.api.core.CohereException; +import com.cohere.api.core.MediaTypes; +import com.cohere.api.core.ObjectMappers; import com.cohere.api.core.RequestOptions; +import com.cohere.api.core.ResponseBodyReader; +import com.cohere.api.core.Stream; +import com.cohere.api.errors.BadRequestError; +import com.cohere.api.errors.ClientClosedRequestError; +import com.cohere.api.errors.ForbiddenError; +import com.cohere.api.errors.GatewayTimeoutError; +import com.cohere.api.errors.InternalServerError; +import com.cohere.api.errors.InvalidTokenError; +import com.cohere.api.errors.NotFoundError; +import com.cohere.api.errors.NotImplementedError; +import com.cohere.api.errors.ServiceUnavailableError; +import com.cohere.api.errors.TooManyRequestsError; +import com.cohere.api.errors.UnauthorizedError; +import com.cohere.api.errors.UnprocessableEntityError; import com.cohere.api.resources.v2.requests.V2ChatRequest; import com.cohere.api.resources.v2.requests.V2ChatStreamRequest; import com.cohere.api.resources.v2.requests.V2EmbedRequest; import com.cohere.api.resources.v2.requests.V2RerankRequest; -import com.cohere.api.resources.v2.types.V2ChatResponse; -import com.cohere.api.resources.v2.types.V2ChatStreamResponse; import com.cohere.api.resources.v2.types.V2RerankResponse; +import com.cohere.api.types.ChatResponseV2; import com.cohere.api.types.EmbedByTypeResponse; +import com.cohere.api.types.StreamedChatResponseV2; +import com.fasterxml.jackson.core.JsonProcessingException; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; public class V2Client { protected final ClientOptions clientOptions; - private final RawV2Client rawClient; - public V2Client(ClientOptions clientOptions) { this.clientOptions = clientOptions; - this.rawClient = new RawV2Client(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawV2Client withRawResponse() { - return this.rawClient; } /** * Generates a text response to a user message. To learn how to use the Chat API and RAG follow our Text Generation guides. *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    */ - public Iterable chatStream(V2ChatStreamRequest request) { - return this.rawClient.chatStream(request).body(); + public Iterable chatStream(V2ChatStreamRequest request) { + return chatStream(request, null); } /** * Generates a text response to a user message. To learn how to use the Chat API and RAG follow our Text Generation guides. *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    */ - public Iterable chatStream(V2ChatStreamRequest request, RequestOptions requestOptions) { - return this.rawClient.chatStream(request, requestOptions).body(); + public Iterable chatStream(V2ChatStreamRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/chat") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try { + Response response = client.newCall(okhttpRequest).execute(); + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new Stream( + StreamedChatResponseV2.class, new ResponseBodyReader(response), "\n"); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * Generates a text response to a user message and streams it down, token by token. To learn how to use the Chat API with streaming follow our Text Generation guides. *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    */ - public V2ChatResponse chat(V2ChatRequest request) { - return this.rawClient.chat(request).body(); + public ChatResponseV2 chat(V2ChatRequest request) { + return chat(request, null); } /** * Generates a text response to a user message and streams it down, token by token. To learn how to use the Chat API with streaming follow our Text Generation guides. *

    Follow the Migration Guide for instructions on moving from API v1 to API v2.

    */ - public V2ChatResponse chat(V2ChatRequest request, RequestOptions requestOptions) { - return this.rawClient.chat(request, requestOptions).body(); + public ChatResponseV2 chat(V2ChatRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/chat") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ChatResponseV2.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** @@ -69,7 +234,7 @@ public V2ChatResponse chat(V2ChatRequest request, RequestOptions requestOptions) *

    If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

    */ public EmbedByTypeResponse embed(V2EmbedRequest request) { - return this.rawClient.embed(request).body(); + return embed(request, null); } /** @@ -78,20 +243,166 @@ public EmbedByTypeResponse embed(V2EmbedRequest request) { *

    If you want to learn more how to use the embedding model, have a look at the Semantic Search Guide.

    */ public EmbedByTypeResponse embed(V2EmbedRequest request, RequestOptions requestOptions) { - return this.rawClient.embed(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/embed") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedByTypeResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } } /** * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. */ public V2RerankResponse rerank(V2RerankRequest request) { - return this.rawClient.rerank(request).body(); + return rerank(request, null); } /** * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score. */ public V2RerankResponse rerank(V2RerankRequest request, RequestOptions requestOptions) { - return this.rawClient.rerank(request, requestOptions).body(); + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/rerank") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V2RerankResponse.class); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 403: + throw new ForbiddenError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 404: + throw new NotFoundError(ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 422: + throw new UnprocessableEntityError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 429: + throw new TooManyRequestsError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 498: + throw new InvalidTokenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 499: + throw new ClientClosedRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 501: + throw new NotImplementedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + case 504: + throw new GatewayTimeoutError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new CohereApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class)); + } 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 b4d05cf..976c804 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 @@ -10,6 +10,7 @@ import com.cohere.api.types.ChatMessageV2; import com.cohere.api.types.CitationOptions; import com.cohere.api.types.ResponseFormatV2; +import com.cohere.api.types.Thinking; import com.cohere.api.types.ToolV2; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; @@ -62,10 +63,14 @@ public final class V2ChatRequest { private final Optional p; + private final Optional returnPrompt; + private final Optional logprobs; private final Optional toolChoice; + private final Optional thinking; + private final Map additionalProperties; private V2ChatRequest( @@ -85,8 +90,10 @@ private V2ChatRequest( Optional presencePenalty, Optional k, Optional p, + Optional returnPrompt, Optional logprobs, Optional toolChoice, + Optional thinking, Map additionalProperties) { this.model = model; this.messages = messages; @@ -104,8 +111,10 @@ private V2ChatRequest( this.presencePenalty = presencePenalty; this.k = k; this.p = p; + this.returnPrompt = returnPrompt; this.logprobs = logprobs; this.toolChoice = toolChoice; + this.thinking = thinking; this.additionalProperties = additionalProperties; } @@ -254,6 +263,14 @@ public Optional getP() { return p; } + /** + * @return Whether to return the prompt in the response. + */ + @JsonProperty("return_prompt") + public Optional getReturnPrompt() { + return returnPrompt; + } + /** * @return Defaults to false. When set to true, the log probabilities of the generated tokens will be included in the response. */ @@ -274,6 +291,11 @@ public Optional getToolChoice() { return toolChoice; } + @JsonProperty("thinking") + public Optional getThinking() { + return thinking; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -302,8 +324,10 @@ private boolean equalTo(V2ChatRequest other) { && presencePenalty.equals(other.presencePenalty) && k.equals(other.k) && p.equals(other.p) + && returnPrompt.equals(other.returnPrompt) && logprobs.equals(other.logprobs) - && toolChoice.equals(other.toolChoice); + && toolChoice.equals(other.toolChoice) + && thinking.equals(other.thinking); } @java.lang.Override @@ -325,8 +349,10 @@ public int hashCode() { this.presencePenalty, this.k, this.p, + this.returnPrompt, this.logprobs, - this.toolChoice); + this.toolChoice, + this.thinking); } @java.lang.Override @@ -339,9 +365,6 @@ public static ModelStage builder() { } public interface ModelStage { - /** - *

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

    - */ _FinalStage model(@NotNull String model); Builder from(V2ChatRequest other); @@ -356,25 +379,14 @@ public interface _FinalStage { _FinalStage addAllMessages(List messages); - /** - *

    A list of tools (functions) available to the model. The model response may contain 'tool_calls' to the specified tools.

    - *

    Learn more in the Tool Use guide.

    - */ _FinalStage tools(Optional> tools); _FinalStage tools(List tools); - /** - *

    When set to true, tool calls in the Assistant message will be forced to follow the tool definition strictly. Learn more in the Structured Outputs (Tools) guide.

    - *

    Note: The first few requests with a new set of tools will take longer to process.

    - */ _FinalStage strictTools(Optional strictTools); _FinalStage strictTools(Boolean strictTools); - /** - *

    A list of relevant documents that the model can cite to generate a more accurate reply. Each document is either a string or document object with content and metadata.

    - */ _FinalStage documents(Optional> documents); _FinalStage documents(List documents); @@ -387,110 +399,71 @@ public interface _FinalStage { _FinalStage responseFormat(ResponseFormatV2 responseFormat); - /** - *

    Used to select the safety instruction inserted into the prompt. Defaults to CONTEXTUAL. - * When OFF is specified, the safety instruction will be omitted.

    - *

    Safety modes are not yet configurable in combination with tools and documents parameters.

    - *

    Note: This parameter is only compatible newer Cohere models, starting with Command R 08-2024 and Command R+ 08-2024.

    - *

    Note: command-r7b-12-2024 and newer models only support "CONTEXTUAL" and "STRICT" modes.

    - */ _FinalStage safetyMode(Optional safetyMode); _FinalStage safetyMode(V2ChatRequestSafetyMode safetyMode); - /** - *

    The maximum number of tokens the model will generate as part of the response.

    - *

    Note: Setting a low value may result in incomplete generations.

    - */ _FinalStage maxTokens(Optional maxTokens); _FinalStage maxTokens(Integer maxTokens); - /** - *

    A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.

    - */ _FinalStage stopSequences(Optional> stopSequences); _FinalStage stopSequences(List stopSequences); - /** - *

    Defaults to 0.3.

    - *

    A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.

    - *

    Randomness can be further maximized by increasing the value of the p parameter.

    - */ _FinalStage temperature(Optional temperature); _FinalStage temperature(Float temperature); - /** - *

    If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed.

    - */ _FinalStage seed(Optional seed); _FinalStage seed(Integer seed); - /** - *

    Defaults to 0.0, min value of 0.0, max value of 1.0. - * 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.

    - */ _FinalStage frequencyPenalty(Optional frequencyPenalty); _FinalStage frequencyPenalty(Float frequencyPenalty); - /** - *

    Defaults to 0.0, min value of 0.0, max value of 1.0. - * Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

    - */ _FinalStage presencePenalty(Optional presencePenalty); _FinalStage presencePenalty(Float presencePenalty); - /** - *

    Ensures that only the top k most likely tokens are considered for generation at each step. When k is set to 0, k-sampling is disabled. - * Defaults to 0, min value of 0, max value of 500.

    - */ _FinalStage k(Optional k); _FinalStage k(Integer k); - /** - *

    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.

    - */ _FinalStage p(Optional p); _FinalStage p(Float p); - /** - *

    Defaults to false. When set to true, the log probabilities of the generated tokens will be included in the response.

    - */ + _FinalStage returnPrompt(Optional returnPrompt); + + _FinalStage returnPrompt(Boolean returnPrompt); + _FinalStage logprobs(Optional logprobs); _FinalStage logprobs(Boolean logprobs); - /** - *

    Used to control whether or not the model will be forced to use a tool when answering. When REQUIRED is specified, the model will be forced to use at least one of the user-defined tools, and the tools parameter must be passed in the request. - * When NONE is specified, the model will be forced not to use one of the specified tools, and give a direct response. - * If tool_choice isn't specified, then the model is free to choose whether to use the specified tools or not.

    - *

    Note: This parameter is only compatible with models Command-r7b and newer.

    - *

    Note: The same functionality can be achieved in /v1/chat using the force_single_step parameter. If force_single_step=true, this is equivalent to specifying REQUIRED. While if force_single_step=true and tool_results are passed, this is equivalent to specifying NONE.

    - */ _FinalStage toolChoice(Optional toolChoice); _FinalStage toolChoice(V2ChatRequestToolChoice toolChoice); + + _FinalStage thinking(Optional thinking); + + _FinalStage thinking(Thinking thinking); } @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder implements ModelStage, _FinalStage { private String model; + private Optional thinking = Optional.empty(); + private Optional toolChoice = Optional.empty(); private Optional logprobs = Optional.empty(); + private Optional returnPrompt = Optional.empty(); + private Optional p = Optional.empty(); private Optional k = Optional.empty(); @@ -544,13 +517,14 @@ public Builder from(V2ChatRequest other) { presencePenalty(other.getPresencePenalty()); k(other.getK()); p(other.getP()); + returnPrompt(other.getReturnPrompt()); logprobs(other.getLogprobs()); toolChoice(other.getToolChoice()); + thinking(other.getThinking()); return this; } /** - *

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

    *

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

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -561,6 +535,19 @@ public _FinalStage model(@NotNull String model) { return this; } + @java.lang.Override + public _FinalStage thinking(Thinking thinking) { + this.thinking = Optional.ofNullable(thinking); + return this; + } + + @java.lang.Override + @JsonSetter(value = "thinking", nulls = Nulls.SKIP) + public _FinalStage thinking(Optional thinking) { + this.thinking = thinking; + return this; + } + /** *

    Used to control whether or not the model will be forced to use a tool when answering. When REQUIRED is specified, the model will be forced to use at least one of the user-defined tools, and the tools parameter must be passed in the request. * When NONE is specified, the model will be forced not to use one of the specified tools, and give a direct response. @@ -575,13 +562,6 @@ public _FinalStage toolChoice(V2ChatRequestToolChoice toolChoice) { return this; } - /** - *

    Used to control whether or not the model will be forced to use a tool when answering. When REQUIRED is specified, the model will be forced to use at least one of the user-defined tools, and the tools parameter must be passed in the request. - * When NONE is specified, the model will be forced not to use one of the specified tools, and give a direct response. - * If tool_choice isn't specified, then the model is free to choose whether to use the specified tools or not.

    - *

    Note: This parameter is only compatible with models Command-r7b and newer.

    - *

    Note: The same functionality can be achieved in /v1/chat using the force_single_step parameter. If force_single_step=true, this is equivalent to specifying REQUIRED. While if force_single_step=true and tool_results are passed, this is equivalent to specifying NONE.

    - */ @java.lang.Override @JsonSetter(value = "tool_choice", nulls = Nulls.SKIP) public _FinalStage toolChoice(Optional toolChoice) { @@ -599,9 +579,6 @@ public _FinalStage logprobs(Boolean logprobs) { return this; } - /** - *

    Defaults to false. When set to true, the log probabilities of the generated tokens will be included in the response.

    - */ @java.lang.Override @JsonSetter(value = "logprobs", nulls = Nulls.SKIP) public _FinalStage logprobs(Optional logprobs) { @@ -610,20 +587,33 @@ public _FinalStage logprobs(Optional logprobs) { } /** - *

    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.

    + *

    Whether to return the prompt in the response.

    * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage p(Float p) { - this.p = Optional.ofNullable(p); + public _FinalStage returnPrompt(Boolean returnPrompt) { + this.returnPrompt = Optional.ofNullable(returnPrompt); + return this; + } + + @java.lang.Override + @JsonSetter(value = "return_prompt", nulls = Nulls.SKIP) + public _FinalStage returnPrompt(Optional returnPrompt) { + this.returnPrompt = returnPrompt; return this; } /** *

    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.

    + * @return Reference to {@code this} so that method calls can be chained together. */ + @java.lang.Override + public _FinalStage p(Float p) { + this.p = Optional.ofNullable(p); + return this; + } + @java.lang.Override @JsonSetter(value = "p", nulls = Nulls.SKIP) public _FinalStage p(Optional p) { @@ -642,10 +632,6 @@ public _FinalStage k(Integer k) { return this; } - /** - *

    Ensures that only the top k most likely tokens are considered for generation at each step. When k is set to 0, k-sampling is disabled. - * Defaults to 0, min value of 0, max value of 500.

    - */ @java.lang.Override @JsonSetter(value = "k", nulls = Nulls.SKIP) public _FinalStage k(Optional k) { @@ -664,10 +650,6 @@ public _FinalStage presencePenalty(Float presencePenalty) { return this; } - /** - *

    Defaults to 0.0, min value of 0.0, max value of 1.0. - * Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

    - */ @java.lang.Override @JsonSetter(value = "presence_penalty", nulls = Nulls.SKIP) public _FinalStage presencePenalty(Optional presencePenalty) { @@ -686,10 +668,6 @@ public _FinalStage frequencyPenalty(Float frequencyPenalty) { return this; } - /** - *

    Defaults to 0.0, min value of 0.0, max value of 1.0. - * 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.

    - */ @java.lang.Override @JsonSetter(value = "frequency_penalty", nulls = Nulls.SKIP) public _FinalStage frequencyPenalty(Optional frequencyPenalty) { @@ -710,12 +688,6 @@ public _FinalStage seed(Integer seed) { return this; } - /** - *

    If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed.

    - */ @java.lang.Override @JsonSetter(value = "seed", nulls = Nulls.SKIP) public _FinalStage seed(Optional seed) { @@ -735,11 +707,6 @@ public _FinalStage temperature(Float temperature) { return this; } - /** - *

    Defaults to 0.3.

    - *

    A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.

    - *

    Randomness can be further maximized by increasing the value of the p parameter.

    - */ @java.lang.Override @JsonSetter(value = "temperature", nulls = Nulls.SKIP) public _FinalStage temperature(Optional temperature) { @@ -757,9 +724,6 @@ public _FinalStage stopSequences(List stopSequences) { return this; } - /** - *

    A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.

    - */ @java.lang.Override @JsonSetter(value = "stop_sequences", nulls = Nulls.SKIP) public _FinalStage stopSequences(Optional> stopSequences) { @@ -778,10 +742,6 @@ public _FinalStage maxTokens(Integer maxTokens) { return this; } - /** - *

    The maximum number of tokens the model will generate as part of the response.

    - *

    Note: Setting a low value may result in incomplete generations.

    - */ @java.lang.Override @JsonSetter(value = "max_tokens", nulls = Nulls.SKIP) public _FinalStage maxTokens(Optional maxTokens) { @@ -803,13 +763,6 @@ public _FinalStage safetyMode(V2ChatRequestSafetyMode safetyMode) { return this; } - /** - *

    Used to select the safety instruction inserted into the prompt. Defaults to CONTEXTUAL. - * When OFF is specified, the safety instruction will be omitted.

    - *

    Safety modes are not yet configurable in combination with tools and documents parameters.

    - *

    Note: This parameter is only compatible newer Cohere models, starting with Command R 08-2024 and Command R+ 08-2024.

    - *

    Note: command-r7b-12-2024 and newer models only support "CONTEXTUAL" and "STRICT" modes.

    - */ @java.lang.Override @JsonSetter(value = "safety_mode", nulls = Nulls.SKIP) public _FinalStage safetyMode(Optional safetyMode) { @@ -853,9 +806,6 @@ public _FinalStage documents(List documents) { return this; } - /** - *

    A list of relevant documents that the model can cite to generate a more accurate reply. Each document is either a string or document object with content and metadata.

    - */ @java.lang.Override @JsonSetter(value = "documents", nulls = Nulls.SKIP) public _FinalStage documents(Optional> documents) { @@ -874,10 +824,6 @@ public _FinalStage strictTools(Boolean strictTools) { return this; } - /** - *

    When set to true, tool calls in the Assistant message will be forced to follow the tool definition strictly. Learn more in the Structured Outputs (Tools) guide.

    - *

    Note: The first few requests with a new set of tools will take longer to process.

    - */ @java.lang.Override @JsonSetter(value = "strict_tools", nulls = Nulls.SKIP) public _FinalStage strictTools(Optional strictTools) { @@ -896,10 +842,6 @@ public _FinalStage tools(List tools) { return this; } - /** - *

    A list of tools (functions) available to the model. The model response may contain 'tool_calls' to the specified tools.

    - *

    Learn more in the Tool Use guide.

    - */ @java.lang.Override @JsonSetter(value = "tools", nulls = Nulls.SKIP) public _FinalStage tools(Optional> tools) { @@ -946,8 +888,10 @@ public V2ChatRequest build() { presencePenalty, k, p, + returnPrompt, logprobs, toolChoice, + thinking, additionalProperties); } } diff --git a/src/main/java/com/cohere/api/resources/v2/requests/V2ChatStreamRequest.java b/src/main/java/com/cohere/api/resources/v2/requests/V2ChatStreamRequest.java index 1da787d..e62d9e0 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 @@ -10,6 +10,7 @@ import com.cohere.api.types.ChatMessageV2; import com.cohere.api.types.CitationOptions; import com.cohere.api.types.ResponseFormatV2; +import com.cohere.api.types.Thinking; import com.cohere.api.types.ToolV2; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; @@ -62,10 +63,14 @@ public final class V2ChatStreamRequest { private final Optional p; + private final Optional returnPrompt; + private final Optional logprobs; private final Optional toolChoice; + private final Optional thinking; + private final Map additionalProperties; private V2ChatStreamRequest( @@ -85,8 +90,10 @@ private V2ChatStreamRequest( Optional presencePenalty, Optional k, Optional p, + Optional returnPrompt, Optional logprobs, Optional toolChoice, + Optional thinking, Map additionalProperties) { this.model = model; this.messages = messages; @@ -104,8 +111,10 @@ private V2ChatStreamRequest( this.presencePenalty = presencePenalty; this.k = k; this.p = p; + this.returnPrompt = returnPrompt; this.logprobs = logprobs; this.toolChoice = toolChoice; + this.thinking = thinking; this.additionalProperties = additionalProperties; } @@ -254,6 +263,14 @@ public Optional getP() { return p; } + /** + * @return Whether to return the prompt in the response. + */ + @JsonProperty("return_prompt") + public Optional getReturnPrompt() { + return returnPrompt; + } + /** * @return Defaults to false. When set to true, the log probabilities of the generated tokens will be included in the response. */ @@ -274,6 +291,11 @@ public Optional getToolChoice() { return toolChoice; } + @JsonProperty("thinking") + public Optional getThinking() { + return thinking; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -302,8 +324,10 @@ private boolean equalTo(V2ChatStreamRequest other) { && presencePenalty.equals(other.presencePenalty) && k.equals(other.k) && p.equals(other.p) + && returnPrompt.equals(other.returnPrompt) && logprobs.equals(other.logprobs) - && toolChoice.equals(other.toolChoice); + && toolChoice.equals(other.toolChoice) + && thinking.equals(other.thinking); } @java.lang.Override @@ -325,8 +349,10 @@ public int hashCode() { this.presencePenalty, this.k, this.p, + this.returnPrompt, this.logprobs, - this.toolChoice); + this.toolChoice, + this.thinking); } @java.lang.Override @@ -339,9 +365,6 @@ public static ModelStage builder() { } public interface ModelStage { - /** - *

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

    - */ _FinalStage model(@NotNull String model); Builder from(V2ChatStreamRequest other); @@ -356,25 +379,14 @@ public interface _FinalStage { _FinalStage addAllMessages(List messages); - /** - *

    A list of tools (functions) available to the model. The model response may contain 'tool_calls' to the specified tools.

    - *

    Learn more in the Tool Use guide.

    - */ _FinalStage tools(Optional> tools); _FinalStage tools(List tools); - /** - *

    When set to true, tool calls in the Assistant message will be forced to follow the tool definition strictly. Learn more in the Structured Outputs (Tools) guide.

    - *

    Note: The first few requests with a new set of tools will take longer to process.

    - */ _FinalStage strictTools(Optional strictTools); _FinalStage strictTools(Boolean strictTools); - /** - *

    A list of relevant documents that the model can cite to generate a more accurate reply. Each document is either a string or document object with content and metadata.

    - */ _FinalStage documents(Optional> documents); _FinalStage documents(List documents); @@ -387,110 +399,71 @@ public interface _FinalStage { _FinalStage responseFormat(ResponseFormatV2 responseFormat); - /** - *

    Used to select the safety instruction inserted into the prompt. Defaults to CONTEXTUAL. - * When OFF is specified, the safety instruction will be omitted.

    - *

    Safety modes are not yet configurable in combination with tools and documents parameters.

    - *

    Note: This parameter is only compatible newer Cohere models, starting with Command R 08-2024 and Command R+ 08-2024.

    - *

    Note: command-r7b-12-2024 and newer models only support "CONTEXTUAL" and "STRICT" modes.

    - */ _FinalStage safetyMode(Optional safetyMode); _FinalStage safetyMode(V2ChatStreamRequestSafetyMode safetyMode); - /** - *

    The maximum number of tokens the model will generate as part of the response.

    - *

    Note: Setting a low value may result in incomplete generations.

    - */ _FinalStage maxTokens(Optional maxTokens); _FinalStage maxTokens(Integer maxTokens); - /** - *

    A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.

    - */ _FinalStage stopSequences(Optional> stopSequences); _FinalStage stopSequences(List stopSequences); - /** - *

    Defaults to 0.3.

    - *

    A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.

    - *

    Randomness can be further maximized by increasing the value of the p parameter.

    - */ _FinalStage temperature(Optional temperature); _FinalStage temperature(Float temperature); - /** - *

    If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed.

    - */ _FinalStage seed(Optional seed); _FinalStage seed(Integer seed); - /** - *

    Defaults to 0.0, min value of 0.0, max value of 1.0. - * 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.

    - */ _FinalStage frequencyPenalty(Optional frequencyPenalty); _FinalStage frequencyPenalty(Float frequencyPenalty); - /** - *

    Defaults to 0.0, min value of 0.0, max value of 1.0. - * Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

    - */ _FinalStage presencePenalty(Optional presencePenalty); _FinalStage presencePenalty(Float presencePenalty); - /** - *

    Ensures that only the top k most likely tokens are considered for generation at each step. When k is set to 0, k-sampling is disabled. - * Defaults to 0, min value of 0, max value of 500.

    - */ _FinalStage k(Optional k); _FinalStage k(Integer k); - /** - *

    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.

    - */ _FinalStage p(Optional p); _FinalStage p(Float p); - /** - *

    Defaults to false. When set to true, the log probabilities of the generated tokens will be included in the response.

    - */ + _FinalStage returnPrompt(Optional returnPrompt); + + _FinalStage returnPrompt(Boolean returnPrompt); + _FinalStage logprobs(Optional logprobs); _FinalStage logprobs(Boolean logprobs); - /** - *

    Used to control whether or not the model will be forced to use a tool when answering. When REQUIRED is specified, the model will be forced to use at least one of the user-defined tools, and the tools parameter must be passed in the request. - * When NONE is specified, the model will be forced not to use one of the specified tools, and give a direct response. - * If tool_choice isn't specified, then the model is free to choose whether to use the specified tools or not.

    - *

    Note: This parameter is only compatible with models Command-r7b and newer.

    - *

    Note: The same functionality can be achieved in /v1/chat using the force_single_step parameter. If force_single_step=true, this is equivalent to specifying REQUIRED. While if force_single_step=true and tool_results are passed, this is equivalent to specifying NONE.

    - */ _FinalStage toolChoice(Optional toolChoice); _FinalStage toolChoice(V2ChatStreamRequestToolChoice toolChoice); + + _FinalStage thinking(Optional thinking); + + _FinalStage thinking(Thinking thinking); } @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder implements ModelStage, _FinalStage { private String model; + private Optional thinking = Optional.empty(); + private Optional toolChoice = Optional.empty(); private Optional logprobs = Optional.empty(); + private Optional returnPrompt = Optional.empty(); + private Optional p = Optional.empty(); private Optional k = Optional.empty(); @@ -544,13 +517,14 @@ public Builder from(V2ChatStreamRequest other) { presencePenalty(other.getPresencePenalty()); k(other.getK()); p(other.getP()); + returnPrompt(other.getReturnPrompt()); logprobs(other.getLogprobs()); toolChoice(other.getToolChoice()); + thinking(other.getThinking()); return this; } /** - *

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

    *

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

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -561,6 +535,19 @@ public _FinalStage model(@NotNull String model) { return this; } + @java.lang.Override + public _FinalStage thinking(Thinking thinking) { + this.thinking = Optional.ofNullable(thinking); + return this; + } + + @java.lang.Override + @JsonSetter(value = "thinking", nulls = Nulls.SKIP) + public _FinalStage thinking(Optional thinking) { + this.thinking = thinking; + return this; + } + /** *

    Used to control whether or not the model will be forced to use a tool when answering. When REQUIRED is specified, the model will be forced to use at least one of the user-defined tools, and the tools parameter must be passed in the request. * When NONE is specified, the model will be forced not to use one of the specified tools, and give a direct response. @@ -575,13 +562,6 @@ public _FinalStage toolChoice(V2ChatStreamRequestToolChoice toolChoice) { return this; } - /** - *

    Used to control whether or not the model will be forced to use a tool when answering. When REQUIRED is specified, the model will be forced to use at least one of the user-defined tools, and the tools parameter must be passed in the request. - * When NONE is specified, the model will be forced not to use one of the specified tools, and give a direct response. - * If tool_choice isn't specified, then the model is free to choose whether to use the specified tools or not.

    - *

    Note: This parameter is only compatible with models Command-r7b and newer.

    - *

    Note: The same functionality can be achieved in /v1/chat using the force_single_step parameter. If force_single_step=true, this is equivalent to specifying REQUIRED. While if force_single_step=true and tool_results are passed, this is equivalent to specifying NONE.

    - */ @java.lang.Override @JsonSetter(value = "tool_choice", nulls = Nulls.SKIP) public _FinalStage toolChoice(Optional toolChoice) { @@ -599,9 +579,6 @@ public _FinalStage logprobs(Boolean logprobs) { return this; } - /** - *

    Defaults to false. When set to true, the log probabilities of the generated tokens will be included in the response.

    - */ @java.lang.Override @JsonSetter(value = "logprobs", nulls = Nulls.SKIP) public _FinalStage logprobs(Optional logprobs) { @@ -610,20 +587,33 @@ public _FinalStage logprobs(Optional logprobs) { } /** - *

    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.

    + *

    Whether to return the prompt in the response.

    * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage p(Float p) { - this.p = Optional.ofNullable(p); + public _FinalStage returnPrompt(Boolean returnPrompt) { + this.returnPrompt = Optional.ofNullable(returnPrompt); + return this; + } + + @java.lang.Override + @JsonSetter(value = "return_prompt", nulls = Nulls.SKIP) + public _FinalStage returnPrompt(Optional returnPrompt) { + this.returnPrompt = returnPrompt; return this; } /** *

    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.

    + * @return Reference to {@code this} so that method calls can be chained together. */ + @java.lang.Override + public _FinalStage p(Float p) { + this.p = Optional.ofNullable(p); + return this; + } + @java.lang.Override @JsonSetter(value = "p", nulls = Nulls.SKIP) public _FinalStage p(Optional p) { @@ -642,10 +632,6 @@ public _FinalStage k(Integer k) { return this; } - /** - *

    Ensures that only the top k most likely tokens are considered for generation at each step. When k is set to 0, k-sampling is disabled. - * Defaults to 0, min value of 0, max value of 500.

    - */ @java.lang.Override @JsonSetter(value = "k", nulls = Nulls.SKIP) public _FinalStage k(Optional k) { @@ -664,10 +650,6 @@ public _FinalStage presencePenalty(Float presencePenalty) { return this; } - /** - *

    Defaults to 0.0, min value of 0.0, max value of 1.0. - * Used to reduce repetitiveness of generated tokens. Similar to frequency_penalty, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.

    - */ @java.lang.Override @JsonSetter(value = "presence_penalty", nulls = Nulls.SKIP) public _FinalStage presencePenalty(Optional presencePenalty) { @@ -686,10 +668,6 @@ public _FinalStage frequencyPenalty(Float frequencyPenalty) { return this; } - /** - *

    Defaults to 0.0, min value of 0.0, max value of 1.0. - * 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.

    - */ @java.lang.Override @JsonSetter(value = "frequency_penalty", nulls = Nulls.SKIP) public _FinalStage frequencyPenalty(Optional frequencyPenalty) { @@ -710,12 +688,6 @@ public _FinalStage seed(Integer seed) { return this; } - /** - *

    If specified, the backend will make a best effort to sample tokens - * deterministically, such that repeated requests with the same - * seed and parameters should return the same result. However, - * determinism cannot be totally guaranteed.

    - */ @java.lang.Override @JsonSetter(value = "seed", nulls = Nulls.SKIP) public _FinalStage seed(Optional seed) { @@ -735,11 +707,6 @@ public _FinalStage temperature(Float temperature) { return this; } - /** - *

    Defaults to 0.3.

    - *

    A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.

    - *

    Randomness can be further maximized by increasing the value of the p parameter.

    - */ @java.lang.Override @JsonSetter(value = "temperature", nulls = Nulls.SKIP) public _FinalStage temperature(Optional temperature) { @@ -757,9 +724,6 @@ public _FinalStage stopSequences(List stopSequences) { return this; } - /** - *

    A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.

    - */ @java.lang.Override @JsonSetter(value = "stop_sequences", nulls = Nulls.SKIP) public _FinalStage stopSequences(Optional> stopSequences) { @@ -778,10 +742,6 @@ public _FinalStage maxTokens(Integer maxTokens) { return this; } - /** - *

    The maximum number of tokens the model will generate as part of the response.

    - *

    Note: Setting a low value may result in incomplete generations.

    - */ @java.lang.Override @JsonSetter(value = "max_tokens", nulls = Nulls.SKIP) public _FinalStage maxTokens(Optional maxTokens) { @@ -803,13 +763,6 @@ public _FinalStage safetyMode(V2ChatStreamRequestSafetyMode safetyMode) { return this; } - /** - *

    Used to select the safety instruction inserted into the prompt. Defaults to CONTEXTUAL. - * When OFF is specified, the safety instruction will be omitted.

    - *

    Safety modes are not yet configurable in combination with tools and documents parameters.

    - *

    Note: This parameter is only compatible newer Cohere models, starting with Command R 08-2024 and Command R+ 08-2024.

    - *

    Note: command-r7b-12-2024 and newer models only support "CONTEXTUAL" and "STRICT" modes.

    - */ @java.lang.Override @JsonSetter(value = "safety_mode", nulls = Nulls.SKIP) public _FinalStage safetyMode(Optional safetyMode) { @@ -853,9 +806,6 @@ public _FinalStage documents(List documents) { return this; } - /** - *

    A list of relevant documents that the model can cite to generate a more accurate reply. Each document is either a string or document object with content and metadata.

    - */ @java.lang.Override @JsonSetter(value = "documents", nulls = Nulls.SKIP) public _FinalStage documents(Optional> documents) { @@ -874,10 +824,6 @@ public _FinalStage strictTools(Boolean strictTools) { return this; } - /** - *

    When set to true, tool calls in the Assistant message will be forced to follow the tool definition strictly. Learn more in the Structured Outputs (Tools) guide.

    - *

    Note: The first few requests with a new set of tools will take longer to process.

    - */ @java.lang.Override @JsonSetter(value = "strict_tools", nulls = Nulls.SKIP) public _FinalStage strictTools(Optional strictTools) { @@ -896,10 +842,6 @@ public _FinalStage tools(List tools) { return this; } - /** - *

    A list of tools (functions) available to the model. The model response may contain 'tool_calls' to the specified tools.

    - *

    Learn more in the Tool Use guide.

    - */ @java.lang.Override @JsonSetter(value = "tools", nulls = Nulls.SKIP) public _FinalStage tools(Optional> tools) { @@ -946,8 +888,10 @@ public V2ChatStreamRequest build() { presencePenalty, k, p, + returnPrompt, logprobs, toolChoice, + thinking, additionalProperties); } } diff --git a/src/main/java/com/cohere/api/resources/v2/requests/V2EmbedRequest.java b/src/main/java/com/cohere/api/resources/v2/requests/V2EmbedRequest.java index 3556fcf..dfb21df 100644 --- a/src/main/java/com/cohere/api/resources/v2/requests/V2EmbedRequest.java +++ b/src/main/java/com/cohere/api/resources/v2/requests/V2EmbedRequest.java @@ -197,9 +197,6 @@ public static ModelStage builder() { } public interface ModelStage { - /** - *

    ID of one of the available Embedding models.

    - */ InputTypeStage model(@NotNull String model); Builder from(V2EmbedRequest other); @@ -212,63 +209,30 @@ public interface InputTypeStage { public interface _FinalStage { V2EmbedRequest build(); - /** - *

    An array of strings for the model to embed. Maximum number of texts per call is 96.

    - */ _FinalStage texts(Optional> texts); _FinalStage texts(List texts); - /** - *

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

    - *

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

    - *

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

    - */ _FinalStage images(Optional> images); _FinalStage images(List images); - /** - *

    An array of inputs for the model to embed. Maximum number of inputs per call is 96. An input can contain a mix of text and image components.

    - */ _FinalStage inputs(Optional> inputs); _FinalStage inputs(List inputs); - /** - *

    The maximum number of tokens to embed per input. If the input text is longer than this, it will be truncated according to the truncate parameter.

    - */ _FinalStage maxTokens(Optional maxTokens); _FinalStage maxTokens(Integer maxTokens); - /** - *

    The number of dimensions of the output embedding. This is only available for embed-v4 and newer models. - * Possible values are 256, 512, 1024, and 1536. The default is 1536.

    - */ _FinalStage outputDimension(Optional outputDimension); _FinalStage outputDimension(Integer outputDimension); - /** - *

    Specifies the types of embeddings you want to get back. Can be one or more of the following types.

    - *
      - *
    • "float": Use this when you want to get back the default float embeddings. Supported with all Embed models.
    • - *
    • "int8": Use this when you want to get back signed int8 embeddings. Supported with Embed v3.0 and newer Embed models.
    • - *
    • "uint8": Use this when you want to get back unsigned int8 embeddings. Supported with Embed v3.0 and newer Embed models.
    • - *
    • "binary": Use this when you want to get back signed binary embeddings. Supported with Embed v3.0 and newer Embed models.
    • - *
    • "ubinary": Use this when you want to get back unsigned binary embeddings. Supported with Embed v3.0 and newer Embed models.
    • - *
    - */ _FinalStage embeddingTypes(Optional> embeddingTypes); _FinalStage embeddingTypes(List embeddingTypes); - /** - *

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

    - *

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

    - *

    If NONE is selected, when the input exceeds the maximum input token length an error will be returned.

    - */ _FinalStage truncate(Optional truncate); _FinalStage truncate(V2EmbedRequestTruncate truncate); @@ -314,7 +278,6 @@ public Builder from(V2EmbedRequest other) { } /** - *

    ID of one of the available Embedding models.

    *

    ID of one of the available Embedding models.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -344,11 +307,6 @@ public _FinalStage truncate(V2EmbedRequestTruncate truncate) { return this; } - /** - *

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

    - *

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

    - *

    If NONE is selected, when the input exceeds the maximum input token length an error will be returned.

    - */ @java.lang.Override @JsonSetter(value = "truncate", nulls = Nulls.SKIP) public _FinalStage truncate(Optional truncate) { @@ -373,16 +331,6 @@ public _FinalStage embeddingTypes(List embeddingTypes) { return this; } - /** - *

    Specifies the types of embeddings you want to get back. Can be one or more of the following types.

    - *
      - *
    • "float": Use this when you want to get back the default float embeddings. Supported with all Embed models.
    • - *
    • "int8": Use this when you want to get back signed int8 embeddings. Supported with Embed v3.0 and newer Embed models.
    • - *
    • "uint8": Use this when you want to get back unsigned int8 embeddings. Supported with Embed v3.0 and newer Embed models.
    • - *
    • "binary": Use this when you want to get back signed binary embeddings. Supported with Embed v3.0 and newer Embed models.
    • - *
    • "ubinary": Use this when you want to get back unsigned binary embeddings. Supported with Embed v3.0 and newer Embed models.
    • - *
    - */ @java.lang.Override @JsonSetter(value = "embedding_types", nulls = Nulls.SKIP) public _FinalStage embeddingTypes(Optional> embeddingTypes) { @@ -401,10 +349,6 @@ public _FinalStage outputDimension(Integer outputDimension) { return this; } - /** - *

    The number of dimensions of the output embedding. This is only available for embed-v4 and newer models. - * Possible values are 256, 512, 1024, and 1536. The default is 1536.

    - */ @java.lang.Override @JsonSetter(value = "output_dimension", nulls = Nulls.SKIP) public _FinalStage outputDimension(Optional outputDimension) { @@ -422,9 +366,6 @@ public _FinalStage maxTokens(Integer maxTokens) { return this; } - /** - *

    The maximum number of tokens to embed per input. If the input text is longer than this, it will be truncated according to the truncate parameter.

    - */ @java.lang.Override @JsonSetter(value = "max_tokens", nulls = Nulls.SKIP) public _FinalStage maxTokens(Optional maxTokens) { @@ -442,9 +383,6 @@ public _FinalStage inputs(List inputs) { return this; } - /** - *

    An array of inputs for the model to embed. Maximum number of inputs per call is 96. An input can contain a mix of text and image components.

    - */ @java.lang.Override @JsonSetter(value = "inputs", nulls = Nulls.SKIP) public _FinalStage inputs(Optional> inputs) { @@ -464,11 +402,6 @@ public _FinalStage images(List images) { return this; } - /** - *

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

    - *

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

    - *

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

    - */ @java.lang.Override @JsonSetter(value = "images", nulls = Nulls.SKIP) public _FinalStage images(Optional> images) { @@ -486,9 +419,6 @@ public _FinalStage texts(List texts) { return this; } - /** - *

    An array of strings for the model to embed. Maximum number of texts per call is 96.

    - */ @java.lang.Override @JsonSetter(value = "texts", nulls = Nulls.SKIP) public _FinalStage texts(Optional> texts) { diff --git a/src/main/java/com/cohere/api/resources/v2/requests/V2RerankRequest.java b/src/main/java/com/cohere/api/resources/v2/requests/V2RerankRequest.java index 0089220..2f10245 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 @@ -31,6 +31,8 @@ public final class V2RerankRequest { private final Optional topN; + private final Optional returnDocuments; + private final Optional maxTokensPerDoc; private final Map additionalProperties; @@ -40,12 +42,14 @@ private V2RerankRequest( String query, List documents, Optional topN, + Optional returnDocuments, Optional maxTokensPerDoc, Map additionalProperties) { this.model = model; this.query = query; this.documents = documents; this.topN = topN; + this.returnDocuments = returnDocuments; this.maxTokensPerDoc = maxTokensPerDoc; this.additionalProperties = additionalProperties; } @@ -85,6 +89,17 @@ public Optional getTopN() { return topN; } + /** + * @return
      + *
    • If false, returns results without the doc text - the api will return a list of {index, relevance score} where index is inferred from the list passed into the request.
    • + *
    • If true, returns results with the doc text passed in - the api will return an ordered list of {index, text, relevance score} where index + text refers to the list passed into the request.
    • + *
    + */ + @JsonProperty("return_documents") + public Optional getReturnDocuments() { + return returnDocuments; + } + /** * @return Defaults to 4096. Long documents will be automatically truncated to the specified number of tokens. */ @@ -109,12 +124,14 @@ private boolean equalTo(V2RerankRequest other) { && query.equals(other.query) && documents.equals(other.documents) && topN.equals(other.topN) + && returnDocuments.equals(other.returnDocuments) && maxTokensPerDoc.equals(other.maxTokensPerDoc); } @java.lang.Override public int hashCode() { - return Objects.hash(this.model, this.query, this.documents, this.topN, this.maxTokensPerDoc); + return Objects.hash( + this.model, this.query, this.documents, this.topN, this.returnDocuments, this.maxTokensPerDoc); } @java.lang.Override @@ -127,46 +144,32 @@ public static ModelStage builder() { } public interface ModelStage { - /** - *

    The identifier of the model to use, eg rerank-v3.5.

    - */ QueryStage model(@NotNull String model); Builder from(V2RerankRequest other); } public interface QueryStage { - /** - *

    The search query

    - */ _FinalStage query(@NotNull String query); } public interface _FinalStage { V2RerankRequest build(); - /** - *

    A list of texts that will be compared to the query. - * For optimal performance we recommend against sending more than 1,000 documents in a single request.

    - *

    Note: long documents will automatically be truncated to the value of max_tokens_per_doc.

    - *

    Note: structured data should be formatted as YAML strings for best performance.

    - */ _FinalStage documents(List documents); _FinalStage addDocuments(String documents); _FinalStage addAllDocuments(List documents); - /** - *

    Limits the number of returned rerank results to the specified value. If not passed, all the rerank results will be returned.

    - */ _FinalStage topN(Optional topN); _FinalStage topN(Integer topN); - /** - *

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

    - */ + _FinalStage returnDocuments(Optional returnDocuments); + + _FinalStage returnDocuments(Boolean returnDocuments); + _FinalStage maxTokensPerDoc(Optional maxTokensPerDoc); _FinalStage maxTokensPerDoc(Integer maxTokensPerDoc); @@ -180,6 +183,8 @@ public static final class Builder implements ModelStage, QueryStage, _FinalStage private Optional maxTokensPerDoc = Optional.empty(); + private Optional returnDocuments = Optional.empty(); + private Optional topN = Optional.empty(); private List documents = new ArrayList<>(); @@ -195,12 +200,12 @@ public Builder from(V2RerankRequest other) { query(other.getQuery()); documents(other.getDocuments()); topN(other.getTopN()); + returnDocuments(other.getReturnDocuments()); maxTokensPerDoc(other.getMaxTokensPerDoc()); return this; } /** - *

    The identifier of the model to use, eg rerank-v3.5.

    *

    The identifier of the model to use, eg rerank-v3.5.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -212,7 +217,6 @@ public QueryStage model(@NotNull String model) { } /** - *

    The search query

    *

    The search query

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -233,9 +237,6 @@ public _FinalStage maxTokensPerDoc(Integer maxTokensPerDoc) { return this; } - /** - *

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

    - */ @java.lang.Override @JsonSetter(value = "max_tokens_per_doc", nulls = Nulls.SKIP) public _FinalStage maxTokensPerDoc(Optional maxTokensPerDoc) { @@ -244,18 +245,35 @@ public _FinalStage maxTokensPerDoc(Optional maxTokensPerDoc) { } /** - *

    Limits the number of returned rerank results to the specified value. If not passed, all the rerank results will be returned.

    + *
      + *
    • If false, returns results without the doc text - the api will return a list of {index, relevance score} where index is inferred from the list passed into the request.
    • + *
    • If true, returns results with the doc text passed in - the api will return an ordered list of {index, text, relevance score} where index + text refers to the list passed into the request.
    • + *
    * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage topN(Integer topN) { - this.topN = Optional.ofNullable(topN); + public _FinalStage returnDocuments(Boolean returnDocuments) { + this.returnDocuments = Optional.ofNullable(returnDocuments); + return this; + } + + @java.lang.Override + @JsonSetter(value = "return_documents", nulls = Nulls.SKIP) + public _FinalStage returnDocuments(Optional returnDocuments) { + this.returnDocuments = returnDocuments; return this; } /** *

    Limits the number of returned rerank results to the specified value. If not passed, all the rerank results will be returned.

    + * @return Reference to {@code this} so that method calls can be chained together. */ + @java.lang.Override + public _FinalStage topN(Integer topN) { + this.topN = Optional.ofNullable(topN); + return this; + } + @java.lang.Override @JsonSetter(value = "top_n", nulls = Nulls.SKIP) public _FinalStage topN(Optional topN) { @@ -289,12 +307,6 @@ public _FinalStage addDocuments(String documents) { return this; } - /** - *

    A list of texts that will be compared to the query. - * For optimal performance we recommend against sending more than 1,000 documents in a single request.

    - *

    Note: long documents will automatically be truncated to the value of max_tokens_per_doc.

    - *

    Note: structured data should be formatted as YAML strings for best performance.

    - */ @java.lang.Override @JsonSetter(value = "documents", nulls = Nulls.SKIP) public _FinalStage documents(List documents) { @@ -305,7 +317,8 @@ public _FinalStage documents(List documents) { @java.lang.Override public V2RerankRequest build() { - return new V2RerankRequest(model, query, documents, topN, maxTokensPerDoc, additionalProperties); + return new V2RerankRequest( + model, query, documents, topN, returnDocuments, maxTokensPerDoc, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestDocumentsItem.java b/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestDocumentsItem.java index 6a0d6fd..7f0646c 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 @@ -30,7 +30,6 @@ public Object get() { return this.value; } - @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if (this.type == 0) { return visitor.visit((String) this.value); @@ -80,7 +79,7 @@ static final class Deserializer extends StdDeserializer T visit(Visitor visitor) { if (this.type == 0) { return visitor.visit((String) this.value); @@ -80,7 +79,7 @@ static final class Deserializer extends StdDeserializerAn ordered list of ranked documents

    - */ @JsonSetter(value = "results", nulls = Nulls.SKIP) public Builder results(List results) { this.results.clear(); diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponseResultsItem.java b/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponseResultsItem.java index 54f0ae3..948f487 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponseResultsItem.java +++ b/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponseResultsItem.java @@ -10,26 +10,43 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonDeserialize(builder = V2RerankResponseResultsItem.Builder.class) public final class V2RerankResponseResultsItem { + private final Optional document; + private final int index; private final float relevanceScore; private final Map additionalProperties; - private V2RerankResponseResultsItem(int index, float relevanceScore, Map additionalProperties) { + private V2RerankResponseResultsItem( + Optional document, + int index, + float relevanceScore, + Map additionalProperties) { + this.document = document; this.index = index; this.relevanceScore = relevanceScore; this.additionalProperties = additionalProperties; } + /** + * @return If return_documents is set as false this will return none, if true it will return the documents passed in + */ + @JsonProperty("document") + public Optional getDocument() { + return document; + } + /** * @return Corresponds to the index in the original list of documents to which the ranked document belongs. (i.e. if the first value in the results object has an index value of 3, it means in the list of documents passed in, the document at index=3 had the highest relevance) */ @@ -58,12 +75,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(V2RerankResponseResultsItem other) { - return index == other.index && relevanceScore == other.relevanceScore; + return document.equals(other.document) && index == other.index && relevanceScore == other.relevanceScore; } @java.lang.Override public int hashCode() { - return Objects.hash(this.index, this.relevanceScore); + return Objects.hash(this.document, this.index, this.relevanceScore); } @java.lang.Override @@ -76,23 +93,21 @@ public static IndexStage builder() { } public interface IndexStage { - /** - *

    Corresponds to the index in the original list of documents to which the ranked document belongs. (i.e. if the first value in the results object has an index value of 3, it means in the list of documents passed in, the document at index=3 had the highest relevance)

    - */ RelevanceScoreStage index(int index); Builder from(V2RerankResponseResultsItem other); } public interface RelevanceScoreStage { - /** - *

    Relevance scores are normalized to be in the range [0, 1]. Scores close to 1 indicate a high relevance to the query, and scores closer to 0 indicate low relevance. It is not accurate to assume a score of 0.9 means the document is 2x more relevant than a document with a score of 0.45

    - */ _FinalStage relevanceScore(float relevanceScore); } public interface _FinalStage { V2RerankResponseResultsItem build(); + + _FinalStage document(Optional document); + + _FinalStage document(V2RerankResponseResultsItemDocument document); } @JsonIgnoreProperties(ignoreUnknown = true) @@ -101,6 +116,8 @@ public static final class Builder implements IndexStage, RelevanceScoreStage, _F private float relevanceScore; + private Optional document = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -108,13 +125,13 @@ private Builder() {} @java.lang.Override public Builder from(V2RerankResponseResultsItem other) { + document(other.getDocument()); index(other.getIndex()); relevanceScore(other.getRelevanceScore()); return this; } /** - *

    Corresponds to the index in the original list of documents to which the ranked document belongs. (i.e. if the first value in the results object has an index value of 3, it means in the list of documents passed in, the document at index=3 had the highest relevance)

    *

    Corresponds to the index in the original list of documents to which the ranked document belongs. (i.e. if the first value in the results object has an index value of 3, it means in the list of documents passed in, the document at index=3 had the highest relevance)

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -126,7 +143,6 @@ public RelevanceScoreStage index(int index) { } /** - *

    Relevance scores are normalized to be in the range [0, 1]. Scores close to 1 indicate a high relevance to the query, and scores closer to 0 indicate low relevance. It is not accurate to assume a score of 0.9 means the document is 2x more relevant than a document with a score of 0.45

    *

    Relevance scores are normalized to be in the range [0, 1]. Scores close to 1 indicate a high relevance to the query, and scores closer to 0 indicate low relevance. It is not accurate to assume a score of 0.9 means the document is 2x more relevant than a document with a score of 0.45

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -137,9 +153,26 @@ public _FinalStage relevanceScore(float relevanceScore) { return this; } + /** + *

    If return_documents is set as false this will return none, if true it will return the documents passed in

    + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage document(V2RerankResponseResultsItemDocument document) { + this.document = Optional.ofNullable(document); + return this; + } + + @java.lang.Override + @JsonSetter(value = "document", nulls = Nulls.SKIP) + public _FinalStage document(Optional document) { + this.document = document; + return this; + } + @java.lang.Override public V2RerankResponseResultsItem build() { - return new V2RerankResponseResultsItem(index, relevanceScore, additionalProperties); + return new V2RerankResponseResultsItem(document, index, relevanceScore, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponseResultsItemDocument.java b/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponseResultsItemDocument.java new file mode 100644 index 0000000..345cd61 --- /dev/null +++ b/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponseResultsItemDocument.java @@ -0,0 +1,110 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.v2.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V2RerankResponseResultsItemDocument.Builder.class) +public final class V2RerankResponseResultsItemDocument { + private final String text; + + private final Map additionalProperties; + + private V2RerankResponseResultsItemDocument(String text, Map additionalProperties) { + this.text = text; + this.additionalProperties = additionalProperties; + } + + /** + * @return The text of the document to rerank + */ + @JsonProperty("text") + public String getText() { + return text; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V2RerankResponseResultsItemDocument + && equalTo((V2RerankResponseResultsItemDocument) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V2RerankResponseResultsItemDocument other) { + return text.equals(other.text); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.text); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TextStage builder() { + return new Builder(); + } + + public interface TextStage { + _FinalStage text(@NotNull String text); + + Builder from(V2RerankResponseResultsItemDocument other); + } + + public interface _FinalStage { + V2RerankResponseResultsItemDocument build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TextStage, _FinalStage { + private String text; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(V2RerankResponseResultsItemDocument other) { + text(other.getText()); + return this; + } + + /** + *

    The text of the document to rerank

    + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("text") + public _FinalStage text(@NotNull String text) { + this.text = Objects.requireNonNull(text, "text must not be null"); + return this; + } + + @java.lang.Override + public V2RerankResponseResultsItemDocument build() { + return new V2RerankResponseResultsItemDocument(text, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/types/ApiMetaBilledUnits.java b/src/main/java/com/cohere/api/types/ApiMetaBilledUnits.java index 72f11eb..6382b4a 100644 --- a/src/main/java/com/cohere/api/types/ApiMetaBilledUnits.java +++ b/src/main/java/com/cohere/api/types/ApiMetaBilledUnits.java @@ -146,9 +146,6 @@ public Builder from(ApiMetaBilledUnits other) { return this; } - /** - *

    The number of billed images.

    - */ @JsonSetter(value = "images", nulls = Nulls.SKIP) public Builder images(Optional images) { this.images = images; @@ -160,9 +157,6 @@ public Builder images(Double images) { return this; } - /** - *

    The number of billed input tokens.

    - */ @JsonSetter(value = "input_tokens", nulls = Nulls.SKIP) public Builder inputTokens(Optional inputTokens) { this.inputTokens = inputTokens; @@ -174,9 +168,6 @@ public Builder inputTokens(Double inputTokens) { return this; } - /** - *

    The number of billed output tokens.

    - */ @JsonSetter(value = "output_tokens", nulls = Nulls.SKIP) public Builder outputTokens(Optional outputTokens) { this.outputTokens = outputTokens; @@ -188,9 +179,6 @@ public Builder outputTokens(Double outputTokens) { return this; } - /** - *

    The number of billed search units.

    - */ @JsonSetter(value = "search_units", nulls = Nulls.SKIP) public Builder searchUnits(Optional searchUnits) { this.searchUnits = searchUnits; @@ -202,9 +190,6 @@ public Builder searchUnits(Double searchUnits) { return this; } - /** - *

    The number of billed classifications units.

    - */ @JsonSetter(value = "classifications", nulls = Nulls.SKIP) public Builder classifications(Optional classifications) { this.classifications = classifications; diff --git a/src/main/java/com/cohere/api/types/ApiMetaTokens.java b/src/main/java/com/cohere/api/types/ApiMetaTokens.java index 8e12ac0..9d38875 100644 --- a/src/main/java/com/cohere/api/types/ApiMetaTokens.java +++ b/src/main/java/com/cohere/api/types/ApiMetaTokens.java @@ -95,9 +95,6 @@ public Builder from(ApiMetaTokens other) { return this; } - /** - *

    The number of tokens used as input to the model.

    - */ @JsonSetter(value = "input_tokens", nulls = Nulls.SKIP) public Builder inputTokens(Optional inputTokens) { this.inputTokens = inputTokens; @@ -109,9 +106,6 @@ public Builder inputTokens(Double inputTokens) { return this; } - /** - *

    The number of tokens produced by the model.

    - */ @JsonSetter(value = "output_tokens", nulls = Nulls.SKIP) public Builder outputTokens(Optional outputTokens) { this.outputTokens = outputTokens; diff --git a/src/main/java/com/cohere/api/types/AssistantMessage.java b/src/main/java/com/cohere/api/types/AssistantMessage.java index e4462eb..7495cb0 100644 --- a/src/main/java/com/cohere/api/types/AssistantMessage.java +++ b/src/main/java/com/cohere/api/types/AssistantMessage.java @@ -133,9 +133,6 @@ public Builder toolCalls(List toolCalls) { return this; } - /** - *

    A chain-of-thought style reflection and plan that the model generates when working with Tools.

    - */ @JsonSetter(value = "tool_plan", nulls = Nulls.SKIP) public Builder toolPlan(Optional toolPlan) { this.toolPlan = toolPlan; diff --git a/src/main/java/com/cohere/api/types/AssistantMessageResponse.java b/src/main/java/com/cohere/api/types/AssistantMessageResponse.java index fe1b53d..e3086fd 100644 --- a/src/main/java/com/cohere/api/types/AssistantMessageResponse.java +++ b/src/main/java/com/cohere/api/types/AssistantMessageResponse.java @@ -138,9 +138,6 @@ public Builder toolCalls(List toolCalls) { return this; } - /** - *

    A chain-of-thought style reflection and plan that the model generates when working with Tools.

    - */ @JsonSetter(value = "tool_plan", nulls = Nulls.SKIP) public Builder toolPlan(Optional toolPlan) { this.toolPlan = toolPlan; diff --git a/src/main/java/com/cohere/api/types/AssistantMessageResponseContentItem.java b/src/main/java/com/cohere/api/types/AssistantMessageResponseContentItem.java index c18756e..89c7fa8 100644 --- a/src/main/java/com/cohere/api/types/AssistantMessageResponseContentItem.java +++ b/src/main/java/com/cohere/api/types/AssistantMessageResponseContentItem.java @@ -30,7 +30,7 @@ public static AssistantMessageResponseContentItem text(ChatTextContent value) { return new AssistantMessageResponseContentItem(new TextValue(value)); } - public static AssistantMessageResponseContentItem thinking(Object value) { + public static AssistantMessageResponseContentItem thinking(ChatThinkingContent value) { return new AssistantMessageResponseContentItem(new ThinkingValue(value)); } @@ -53,7 +53,7 @@ public Optional getText() { return Optional.empty(); } - public Optional getThinking() { + public Optional getThinking() { if (isThinking()) { return Optional.of(((ThinkingValue) value).value); } @@ -75,7 +75,7 @@ private Value getValue() { public interface Visitor { T visitText(ChatTextContent text); - T visitThinking(Object thinking); + T visitThinking(ChatThinkingContent thinking); T _visitUnknown(Object unknownType); } @@ -88,7 +88,6 @@ private interface Value { } @JsonTypeName("text") - @JsonIgnoreProperties("type") private static final class TextValue implements Value { @JsonUnwrapped private ChatTextContent value; @@ -127,13 +126,14 @@ public String toString() { } @JsonTypeName("thinking") - @JsonIgnoreProperties("type") private static final class ThinkingValue implements Value { - @JsonProperty("value") - private Object value; + @JsonUnwrapped + private ChatThinkingContent value; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) - private ThinkingValue(@JsonProperty("value") Object value) { + private ThinkingValue() {} + + private ThinkingValue(ChatThinkingContent value) { this.value = value; } @@ -163,7 +163,6 @@ public String toString() { } } - @JsonIgnoreProperties("type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/AssistantMessageV2Content.java b/src/main/java/com/cohere/api/types/AssistantMessageV2Content.java index 369df33..9febdfc 100644 --- a/src/main/java/com/cohere/api/types/AssistantMessageV2Content.java +++ b/src/main/java/com/cohere/api/types/AssistantMessageV2Content.java @@ -31,7 +31,6 @@ public Object get() { return this.value; } - @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if (this.type == 0) { return visitor.visit((String) this.value); @@ -81,7 +80,7 @@ static final class Deserializer extends StdDeserializerThe index of text that the citation starts at, counting from zero. For example, a generation of Hello, world! with a citation on world would have a start value of 7. This is because the citation starts at w, which is the seventh character.

    - */ EndStage start(int start); Builder from(ChatCitation other); } public interface EndStage { - /** - *

    The index of text that the citation ends after, counting from zero. For example, a generation of Hello, world! with a citation on world would have an end value of 11. This is because the citation ends after d, which is the eleventh character.

    - */ TextStage end(int end); } public interface TextStage { - /** - *

    The text of the citation. For example, a generation of Hello, world! with a citation of world would have a text value of world.

    - */ _FinalStage text(@NotNull String text); } public interface _FinalStage { ChatCitation build(); - /** - *

    Identifiers of documents cited by this section of the generated reply.

    - */ _FinalStage documentIds(List documentIds); _FinalStage addDocumentIds(String documentIds); _FinalStage addAllDocumentIds(List documentIds); - /** - *

    The type of citation which indicates what part of the response the citation is for.

    - */ _FinalStage type(Optional type); _FinalStage type(ChatCitationType type); @@ -194,7 +179,6 @@ public Builder from(ChatCitation other) { } /** - *

    The index of text that the citation starts at, counting from zero. For example, a generation of Hello, world! with a citation on world would have a start value of 7. This is because the citation starts at w, which is the seventh character.

    *

    The index of text that the citation starts at, counting from zero. For example, a generation of Hello, world! with a citation on world would have a start value of 7. This is because the citation starts at w, which is the seventh character.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -206,7 +190,6 @@ public EndStage start(int start) { } /** - *

    The index of text that the citation ends after, counting from zero. For example, a generation of Hello, world! with a citation on world would have an end value of 11. This is because the citation ends after d, which is the eleventh character.

    *

    The index of text that the citation ends after, counting from zero. For example, a generation of Hello, world! with a citation on world would have an end value of 11. This is because the citation ends after d, which is the eleventh character.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -218,7 +201,6 @@ public TextStage end(int end) { } /** - *

    The text of the citation. For example, a generation of Hello, world! with a citation of world would have a text value of world.

    *

    The text of the citation. For example, a generation of Hello, world! with a citation of world would have a text value of world.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -239,9 +221,6 @@ public _FinalStage type(ChatCitationType type) { return this; } - /** - *

    The type of citation which indicates what part of the response the citation is for.

    - */ @java.lang.Override @JsonSetter(value = "type", nulls = Nulls.SKIP) public _FinalStage type(Optional type) { @@ -269,9 +248,6 @@ public _FinalStage addDocumentIds(String documentIds) { return this; } - /** - *

    Identifiers of documents cited by this section of the generated reply.

    - */ @java.lang.Override @JsonSetter(value = "document_ids", nulls = Nulls.SKIP) public _FinalStage documentIds(List documentIds) { diff --git a/src/main/java/com/cohere/api/types/ChatCitationGenerationEvent.java b/src/main/java/com/cohere/api/types/ChatCitationGenerationEvent.java index 588a6cd..add3d70 100644 --- a/src/main/java/com/cohere/api/types/ChatCitationGenerationEvent.java +++ b/src/main/java/com/cohere/api/types/ChatCitationGenerationEvent.java @@ -81,9 +81,6 @@ public Builder from(ChatCitationGenerationEvent other) { return this; } - /** - *

    Citations for the generated reply.

    - */ @JsonSetter(value = "citations", nulls = Nulls.SKIP) public Builder citations(List citations) { this.citations.clear(); diff --git a/src/main/java/com/cohere/api/types/ChatConnector.java b/src/main/java/com/cohere/api/types/ChatConnector.java index 832f1e9..77d5edb 100644 --- a/src/main/java/com/cohere/api/types/ChatConnector.java +++ b/src/main/java/com/cohere/api/types/ChatConnector.java @@ -111,9 +111,6 @@ public static IdStage builder() { } public interface IdStage { - /** - *

    The identifier of the connector.

    - */ _FinalStage id(@NotNull String id); Builder from(ChatConnector other); @@ -122,25 +119,14 @@ public interface IdStage { public interface _FinalStage { ChatConnector build(); - /** - *

    When specified, this user access token will be passed to the connector in the Authorization header instead of the Cohere generated one.

    - */ _FinalStage userAccessToken(Optional userAccessToken); _FinalStage userAccessToken(String userAccessToken); - /** - *

    Defaults to false.

    - *

    When true, the request will continue if this connector returned an error.

    - */ _FinalStage continueOnFailure(Optional continueOnFailure); _FinalStage continueOnFailure(Boolean continueOnFailure); - /** - *

    Provides the connector with different settings at request time. The key/value pairs of this object are specific to each connector.

    - *

    For example, the connector web-search supports the site option, which limits search results to the specified domain.

    - */ _FinalStage options(Optional> options); _FinalStage options(Map options); @@ -171,7 +157,6 @@ public Builder from(ChatConnector other) { } /** - *

    The identifier of the connector.

    *

    The identifier of the connector.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -193,10 +178,6 @@ public _FinalStage options(Map options) { return this; } - /** - *

    Provides the connector with different settings at request time. The key/value pairs of this object are specific to each connector.

    - *

    For example, the connector web-search supports the site option, which limits search results to the specified domain.

    - */ @java.lang.Override @JsonSetter(value = "options", nulls = Nulls.SKIP) public _FinalStage options(Optional> options) { @@ -215,10 +196,6 @@ public _FinalStage continueOnFailure(Boolean continueOnFailure) { return this; } - /** - *

    Defaults to false.

    - *

    When true, the request will continue if this connector returned an error.

    - */ @java.lang.Override @JsonSetter(value = "continue_on_failure", nulls = Nulls.SKIP) public _FinalStage continueOnFailure(Optional continueOnFailure) { @@ -236,9 +213,6 @@ public _FinalStage userAccessToken(String userAccessToken) { return this; } - /** - *

    When specified, this user access token will be passed to the connector in the Authorization header instead of the Cohere generated one.

    - */ @java.lang.Override @JsonSetter(value = "user_access_token", nulls = Nulls.SKIP) public _FinalStage userAccessToken(Optional userAccessToken) { diff --git a/src/main/java/com/cohere/api/types/ChatContentDeltaEventDeltaMessageContent.java b/src/main/java/com/cohere/api/types/ChatContentDeltaEventDeltaMessageContent.java index a100ca0..8005c7d 100644 --- a/src/main/java/com/cohere/api/types/ChatContentDeltaEventDeltaMessageContent.java +++ b/src/main/java/com/cohere/api/types/ChatContentDeltaEventDeltaMessageContent.java @@ -20,15 +20,24 @@ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonDeserialize(builder = ChatContentDeltaEventDeltaMessageContent.Builder.class) public final class ChatContentDeltaEventDeltaMessageContent { + private final Optional thinking; + private final Optional text; private final Map additionalProperties; - private ChatContentDeltaEventDeltaMessageContent(Optional text, Map additionalProperties) { + private ChatContentDeltaEventDeltaMessageContent( + Optional thinking, Optional text, Map additionalProperties) { + this.thinking = thinking; this.text = text; this.additionalProperties = additionalProperties; } + @JsonProperty("thinking") + public Optional getThinking() { + return thinking; + } + @JsonProperty("text") public Optional getText() { return text; @@ -47,12 +56,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(ChatContentDeltaEventDeltaMessageContent other) { - return text.equals(other.text); + return thinking.equals(other.thinking) && text.equals(other.text); } @java.lang.Override public int hashCode() { - return Objects.hash(this.text); + return Objects.hash(this.thinking, this.text); } @java.lang.Override @@ -66,6 +75,8 @@ public static Builder builder() { @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder { + private Optional thinking = Optional.empty(); + private Optional text = Optional.empty(); @JsonAnySetter @@ -74,10 +85,22 @@ public static final class Builder { private Builder() {} public Builder from(ChatContentDeltaEventDeltaMessageContent other) { + thinking(other.getThinking()); text(other.getText()); return this; } + @JsonSetter(value = "thinking", nulls = Nulls.SKIP) + public Builder thinking(Optional thinking) { + this.thinking = thinking; + return this; + } + + public Builder thinking(String thinking) { + this.thinking = Optional.ofNullable(thinking); + return this; + } + @JsonSetter(value = "text", nulls = Nulls.SKIP) public Builder text(Optional text) { this.text = text; @@ -90,7 +113,7 @@ public Builder text(String text) { } public ChatContentDeltaEventDeltaMessageContent build() { - return new ChatContentDeltaEventDeltaMessageContent(text, additionalProperties); + return new ChatContentDeltaEventDeltaMessageContent(thinking, text, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/types/ChatContentStartEventDeltaMessageContent.java b/src/main/java/com/cohere/api/types/ChatContentStartEventDeltaMessageContent.java index 3feacf4..1ac6730 100644 --- a/src/main/java/com/cohere/api/types/ChatContentStartEventDeltaMessageContent.java +++ b/src/main/java/com/cohere/api/types/ChatContentStartEventDeltaMessageContent.java @@ -20,6 +20,8 @@ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonDeserialize(builder = ChatContentStartEventDeltaMessageContent.Builder.class) public final class ChatContentStartEventDeltaMessageContent { + private final Optional thinking; + private final Optional text; private final Optional type; @@ -27,14 +29,21 @@ public final class ChatContentStartEventDeltaMessageContent { private final Map additionalProperties; private ChatContentStartEventDeltaMessageContent( + Optional thinking, Optional text, Optional type, Map additionalProperties) { + this.thinking = thinking; this.text = text; this.type = type; this.additionalProperties = additionalProperties; } + @JsonProperty("thinking") + public Optional getThinking() { + return thinking; + } + @JsonProperty("text") public Optional getText() { return text; @@ -58,12 +67,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(ChatContentStartEventDeltaMessageContent other) { - return text.equals(other.text) && type.equals(other.type); + return thinking.equals(other.thinking) && text.equals(other.text) && type.equals(other.type); } @java.lang.Override public int hashCode() { - return Objects.hash(this.text, this.type); + return Objects.hash(this.thinking, this.text, this.type); } @java.lang.Override @@ -77,6 +86,8 @@ public static Builder builder() { @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder { + private Optional thinking = Optional.empty(); + private Optional text = Optional.empty(); private Optional type = Optional.empty(); @@ -87,11 +98,23 @@ public static final class Builder { private Builder() {} public Builder from(ChatContentStartEventDeltaMessageContent other) { + thinking(other.getThinking()); text(other.getText()); type(other.getType()); return this; } + @JsonSetter(value = "thinking", nulls = Nulls.SKIP) + public Builder thinking(Optional thinking) { + this.thinking = thinking; + return this; + } + + public Builder thinking(String thinking) { + this.thinking = Optional.ofNullable(thinking); + return this; + } + @JsonSetter(value = "text", nulls = Nulls.SKIP) public Builder text(Optional text) { this.text = text; @@ -115,7 +138,7 @@ public Builder type(ChatContentStartEventDeltaMessageContentType type) { } public ChatContentStartEventDeltaMessageContent build() { - return new ChatContentStartEventDeltaMessageContent(text, type, additionalProperties); + return new ChatContentStartEventDeltaMessageContent(thinking, text, type, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/types/ChatDataMetrics.java b/src/main/java/com/cohere/api/types/ChatDataMetrics.java index 2dab26d..2dfaace 100644 --- a/src/main/java/com/cohere/api/types/ChatDataMetrics.java +++ b/src/main/java/com/cohere/api/types/ChatDataMetrics.java @@ -114,9 +114,6 @@ public Builder from(ChatDataMetrics other) { return this; } - /** - *

    The sum of all turns of valid train examples.

    - */ @JsonSetter(value = "num_train_turns", nulls = Nulls.SKIP) public Builder numTrainTurns(Optional numTrainTurns) { this.numTrainTurns = numTrainTurns; @@ -128,9 +125,6 @@ public Builder numTrainTurns(Long numTrainTurns) { return this; } - /** - *

    The sum of all turns of valid eval examples.

    - */ @JsonSetter(value = "num_eval_turns", nulls = Nulls.SKIP) public Builder numEvalTurns(Optional numEvalTurns) { this.numEvalTurns = numEvalTurns; @@ -142,9 +136,6 @@ public Builder numEvalTurns(Long numEvalTurns) { return this; } - /** - *

    The preamble of this dataset.

    - */ @JsonSetter(value = "preamble", nulls = Nulls.SKIP) public Builder preamble(Optional preamble) { this.preamble = preamble; diff --git a/src/main/java/com/cohere/api/types/ChatDocumentSource.java b/src/main/java/com/cohere/api/types/ChatDocumentSource.java index 007605c..3eda18a 100644 --- a/src/main/java/com/cohere/api/types/ChatDocumentSource.java +++ b/src/main/java/com/cohere/api/types/ChatDocumentSource.java @@ -92,9 +92,6 @@ public Builder from(ChatDocumentSource other) { return this; } - /** - *

    The unique identifier of the document

    - */ @JsonSetter(value = "id", nulls = Nulls.SKIP) public Builder id(Optional id) { this.id = id; diff --git a/src/main/java/com/cohere/api/types/ChatMessage.java b/src/main/java/com/cohere/api/types/ChatMessage.java index 75ae70b..e0d9d5c 100644 --- a/src/main/java/com/cohere/api/types/ChatMessage.java +++ b/src/main/java/com/cohere/api/types/ChatMessage.java @@ -77,9 +77,6 @@ public static MessageStage builder() { } public interface MessageStage { - /** - *

    Contents of the chat message.

    - */ _FinalStage message(@NotNull String message); Builder from(ChatMessage other); @@ -112,7 +109,6 @@ public Builder from(ChatMessage other) { } /** - *

    Contents of the chat message.

    *

    Contents of the chat message.

    * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/ChatMessageEndEventDelta.java b/src/main/java/com/cohere/api/types/ChatMessageEndEventDelta.java index 0b0b55f..b140b93 100644 --- a/src/main/java/com/cohere/api/types/ChatMessageEndEventDelta.java +++ b/src/main/java/com/cohere/api/types/ChatMessageEndEventDelta.java @@ -80,9 +80,6 @@ public Builder from(ChatMessageEndEventDelta other) { return this; } - /** - *

    An error message if an error occurred during the generation.

    - */ @JsonSetter(value = "error", nulls = Nulls.SKIP) public Builder error(Optional error) { this.error = error; diff --git a/src/main/java/com/cohere/api/types/ChatMessageStartEvent.java b/src/main/java/com/cohere/api/types/ChatMessageStartEvent.java index ba03a46..5406710 100644 --- a/src/main/java/com/cohere/api/types/ChatMessageStartEvent.java +++ b/src/main/java/com/cohere/api/types/ChatMessageStartEvent.java @@ -92,9 +92,6 @@ public Builder from(ChatMessageStartEvent other) { return this; } - /** - *

    Unique identifier for the generated reply.

    - */ @JsonSetter(value = "id", nulls = Nulls.SKIP) public Builder id(Optional id) { this.id = id; diff --git a/src/main/java/com/cohere/api/types/ChatMessageStartEventDeltaMessage.java b/src/main/java/com/cohere/api/types/ChatMessageStartEventDeltaMessage.java index 36149b0..13e2bd6 100644 --- a/src/main/java/com/cohere/api/types/ChatMessageStartEventDeltaMessage.java +++ b/src/main/java/com/cohere/api/types/ChatMessageStartEventDeltaMessage.java @@ -80,9 +80,6 @@ public Builder from(ChatMessageStartEventDeltaMessage other) { return this; } - /** - *

    The role of the message.

    - */ @JsonSetter(value = "role", nulls = Nulls.SKIP) public Builder role(Optional role) { this.role = role; diff --git a/src/main/java/com/cohere/api/types/ChatMessageV2.java b/src/main/java/com/cohere/api/types/ChatMessageV2.java index 07e2a69..cb2fd0b 100644 --- a/src/main/java/com/cohere/api/types/ChatMessageV2.java +++ b/src/main/java/com/cohere/api/types/ChatMessageV2.java @@ -127,7 +127,6 @@ private interface Value { } @JsonTypeName("user") - @JsonIgnoreProperties("role") private static final class UserValue implements Value { @JsonUnwrapped private UserMessageV2 value; @@ -166,7 +165,6 @@ public String toString() { } @JsonTypeName("assistant") - @JsonIgnoreProperties("role") private static final class AssistantValue implements Value { @JsonUnwrapped private AssistantMessage value; @@ -205,7 +203,6 @@ public String toString() { } @JsonTypeName("system") - @JsonIgnoreProperties("role") private static final class SystemValue implements Value { @JsonUnwrapped private SystemMessageV2 value; @@ -244,7 +241,6 @@ public String toString() { } @JsonTypeName("tool") - @JsonIgnoreProperties("role") private static final class ToolValue implements Value { @JsonUnwrapped private ToolMessageV2 value; @@ -282,7 +278,6 @@ public String toString() { } } - @JsonIgnoreProperties("role") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/ChatRequestConnectorsSearchOptions.java b/src/main/java/com/cohere/api/types/ChatRequestConnectorsSearchOptions.java new file mode 100644 index 0000000..224d6cf --- /dev/null +++ b/src/main/java/com/cohere/api/types/ChatRequestConnectorsSearchOptions.java @@ -0,0 +1,103 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ChatRequestConnectorsSearchOptions.Builder.class) +public final class ChatRequestConnectorsSearchOptions { + private final Optional seed; + + private final Map additionalProperties; + + private ChatRequestConnectorsSearchOptions(Optional seed, Map additionalProperties) { + this.seed = seed; + this.additionalProperties = additionalProperties; + } + + /** + * @return If specified, the backend will make a best effort to sample tokens + * deterministically, such that repeated requests with the same + * seed and parameters should return the same result. However, + * determinism cannot be totally guaranteed. + *

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

    + */ + @JsonProperty("seed") + public Optional getSeed() { + return seed; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ChatRequestConnectorsSearchOptions + && equalTo((ChatRequestConnectorsSearchOptions) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ChatRequestConnectorsSearchOptions other) { + return seed.equals(other.seed); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.seed); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional seed = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ChatRequestConnectorsSearchOptions other) { + seed(other.getSeed()); + return this; + } + + @JsonSetter(value = "seed", nulls = Nulls.SKIP) + public Builder seed(Optional seed) { + this.seed = seed; + return this; + } + + public Builder seed(Integer seed) { + this.seed = Optional.ofNullable(seed); + return this; + } + + public ChatRequestConnectorsSearchOptions build() { + return new ChatRequestConnectorsSearchOptions(seed, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2ChatResponse.java b/src/main/java/com/cohere/api/types/ChatResponseV2.java similarity index 76% rename from src/main/java/com/cohere/api/resources/v2/types/V2ChatResponse.java rename to src/main/java/com/cohere/api/types/ChatResponseV2.java index 5bdb73b..6328f77 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2ChatResponse.java +++ b/src/main/java/com/cohere/api/types/ChatResponseV2.java @@ -1,13 +1,9 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.cohere.api.resources.v2.types; +package com.cohere.api.types; import com.cohere.api.core.ObjectMappers; -import com.cohere.api.types.AssistantMessageResponse; -import com.cohere.api.types.ChatFinishReason; -import com.cohere.api.types.LogprobItem; -import com.cohere.api.types.Usage; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -24,12 +20,14 @@ import org.jetbrains.annotations.NotNull; @JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V2ChatResponse.Builder.class) -public final class V2ChatResponse { +@JsonDeserialize(builder = ChatResponseV2.Builder.class) +public final class ChatResponseV2 { private final String id; private final ChatFinishReason finishReason; + private final Optional prompt; + private final AssistantMessageResponse message; private final Optional usage; @@ -38,15 +36,17 @@ public final class V2ChatResponse { private final Map additionalProperties; - private V2ChatResponse( + private ChatResponseV2( String id, ChatFinishReason finishReason, + Optional prompt, AssistantMessageResponse message, Optional usage, Optional> logprobs, Map additionalProperties) { this.id = id; this.finishReason = finishReason; + this.prompt = prompt; this.message = message; this.usage = usage; this.logprobs = logprobs; @@ -66,6 +66,14 @@ public ChatFinishReason getFinishReason() { return finishReason; } + /** + * @return The prompt that was used. Only present when return_prompt in the request is set to true. + */ + @JsonProperty("prompt") + public Optional getPrompt() { + return prompt; + } + @JsonProperty("message") public AssistantMessageResponse getMessage() { return message; @@ -84,7 +92,7 @@ public Optional> getLogprobs() { @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof V2ChatResponse && equalTo((V2ChatResponse) other); + return other instanceof ChatResponseV2 && equalTo((ChatResponseV2) other); } @JsonAnyGetter @@ -92,9 +100,10 @@ public Map getAdditionalProperties() { return this.additionalProperties; } - private boolean equalTo(V2ChatResponse other) { + private boolean equalTo(ChatResponseV2 other) { return id.equals(other.id) && finishReason.equals(other.finishReason) + && prompt.equals(other.prompt) && message.equals(other.message) && usage.equals(other.usage) && logprobs.equals(other.logprobs); @@ -102,7 +111,7 @@ private boolean equalTo(V2ChatResponse other) { @java.lang.Override public int hashCode() { - return Objects.hash(this.id, this.finishReason, this.message, this.usage, this.logprobs); + return Objects.hash(this.id, this.finishReason, this.prompt, this.message, this.usage, this.logprobs); } @java.lang.Override @@ -115,12 +124,9 @@ public static IdStage builder() { } public interface IdStage { - /** - *

    Unique identifier for the generated reply. Useful for submitting feedback.

    - */ FinishReasonStage id(@NotNull String id); - Builder from(V2ChatResponse other); + Builder from(ChatResponseV2 other); } public interface FinishReasonStage { @@ -132,7 +138,11 @@ public interface MessageStage { } public interface _FinalStage { - V2ChatResponse build(); + ChatResponseV2 build(); + + _FinalStage prompt(Optional prompt); + + _FinalStage prompt(String prompt); _FinalStage usage(Optional usage); @@ -155,15 +165,18 @@ public static final class Builder implements IdStage, FinishReasonStage, Message private Optional usage = Optional.empty(); + private Optional prompt = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); private Builder() {} @java.lang.Override - public Builder from(V2ChatResponse other) { + public Builder from(ChatResponseV2 other) { id(other.getId()); finishReason(other.getFinishReason()); + prompt(other.getPrompt()); message(other.getMessage()); usage(other.getUsage()); logprobs(other.getLogprobs()); @@ -171,7 +184,6 @@ public Builder from(V2ChatResponse other) { } /** - *

    Unique identifier for the generated reply. Useful for submitting feedback.

    *

    Unique identifier for the generated reply. Useful for submitting feedback.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -222,9 +234,26 @@ public _FinalStage usage(Optional usage) { return this; } + /** + *

    The prompt that was used. Only present when return_prompt in the request is set to true.

    + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage prompt(String prompt) { + this.prompt = Optional.ofNullable(prompt); + return this; + } + + @java.lang.Override + @JsonSetter(value = "prompt", nulls = Nulls.SKIP) + public _FinalStage prompt(Optional prompt) { + this.prompt = prompt; + return this; + } + @java.lang.Override - public V2ChatResponse build() { - return new V2ChatResponse(id, finishReason, message, usage, logprobs, additionalProperties); + public ChatResponseV2 build() { + return new ChatResponseV2(id, finishReason, prompt, message, usage, logprobs, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/types/ChatSearchQueriesGenerationEvent.java b/src/main/java/com/cohere/api/types/ChatSearchQueriesGenerationEvent.java index 6bd704c..57c2bb8 100644 --- a/src/main/java/com/cohere/api/types/ChatSearchQueriesGenerationEvent.java +++ b/src/main/java/com/cohere/api/types/ChatSearchQueriesGenerationEvent.java @@ -82,9 +82,6 @@ public Builder from(ChatSearchQueriesGenerationEvent other) { return this; } - /** - *

    Generated search queries, meant to be used as part of the RAG flow.

    - */ @JsonSetter(value = "search_queries", nulls = Nulls.SKIP) public Builder searchQueries(List searchQueries) { this.searchQueries.clear(); diff --git a/src/main/java/com/cohere/api/types/ChatSearchQuery.java b/src/main/java/com/cohere/api/types/ChatSearchQuery.java index a264cee..2c63598 100644 --- a/src/main/java/com/cohere/api/types/ChatSearchQuery.java +++ b/src/main/java/com/cohere/api/types/ChatSearchQuery.java @@ -77,18 +77,12 @@ public static TextStage builder() { } public interface TextStage { - /** - *

    The text of the search query.

    - */ GenerationIdStage text(@NotNull String text); Builder from(ChatSearchQuery other); } public interface GenerationIdStage { - /** - *

    Unique identifier for the generated search query. Useful for submitting feedback.

    - */ _FinalStage generationId(@NotNull String generationId); } @@ -115,7 +109,6 @@ public Builder from(ChatSearchQuery other) { } /** - *

    The text of the search query.

    *

    The text of the search query.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -127,7 +120,6 @@ public GenerationIdStage text(@NotNull String text) { } /** - *

    Unique identifier for the generated search query. Useful for submitting feedback.

    *

    Unique identifier for the generated search query. Useful for submitting feedback.

    * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/ChatSearchResult.java b/src/main/java/com/cohere/api/types/ChatSearchResult.java index 19c3619..4f81c4d 100644 --- a/src/main/java/com/cohere/api/types/ChatSearchResult.java +++ b/src/main/java/com/cohere/api/types/ChatSearchResult.java @@ -122,9 +122,6 @@ public static ConnectorStage builder() { } public interface ConnectorStage { - /** - *

    The connector from which this result comes from.

    - */ _FinalStage connector(@NotNull ChatSearchResultConnector connector); Builder from(ChatSearchResult other); @@ -137,25 +134,16 @@ public interface _FinalStage { _FinalStage searchQuery(ChatSearchQuery searchQuery); - /** - *

    Identifiers of documents found by this search query.

    - */ _FinalStage documentIds(List documentIds); _FinalStage addDocumentIds(String documentIds); _FinalStage addAllDocumentIds(List documentIds); - /** - *

    An error message if the search failed.

    - */ _FinalStage errorMessage(Optional errorMessage); _FinalStage errorMessage(String errorMessage); - /** - *

    Whether a chat request should continue or not if the request to this connector fails.

    - */ _FinalStage continueOnFailure(Optional continueOnFailure); _FinalStage continueOnFailure(Boolean continueOnFailure); @@ -189,7 +177,6 @@ public Builder from(ChatSearchResult other) { } /** - *

    The connector from which this result comes from.

    *

    The connector from which this result comes from.

    * @return Reference to {@code this} so that method calls can be chained together. */ @@ -210,9 +197,6 @@ public _FinalStage continueOnFailure(Boolean continueOnFailure) { return this; } - /** - *

    Whether a chat request should continue or not if the request to this connector fails.

    - */ @java.lang.Override @JsonSetter(value = "continue_on_failure", nulls = Nulls.SKIP) public _FinalStage continueOnFailure(Optional continueOnFailure) { @@ -230,9 +214,6 @@ public _FinalStage errorMessage(String errorMessage) { return this; } - /** - *

    An error message if the search failed.

    - */ @java.lang.Override @JsonSetter(value = "error_message", nulls = Nulls.SKIP) public _FinalStage errorMessage(Optional errorMessage) { @@ -260,9 +241,6 @@ public _FinalStage addDocumentIds(String documentIds) { return this; } - /** - *

    Identifiers of documents found by this search query.

    - */ @java.lang.Override @JsonSetter(value = "document_ids", nulls = Nulls.SKIP) public _FinalStage documentIds(List documentIds) { diff --git a/src/main/java/com/cohere/api/types/ChatSearchResultConnector.java b/src/main/java/com/cohere/api/types/ChatSearchResultConnector.java index 675dc22..40b856e 100644 --- a/src/main/java/com/cohere/api/types/ChatSearchResultConnector.java +++ b/src/main/java/com/cohere/api/types/ChatSearchResultConnector.java @@ -66,9 +66,6 @@ public static IdStage builder() { } public interface IdStage { - /** - *

    The identifier of the connector.

    - */ _FinalStage id(@NotNull String id); Builder from(ChatSearchResultConnector other); @@ -94,7 +91,6 @@ public Builder from(ChatSearchResultConnector other) { } /** - *

    The identifier of the connector.

    *

    The identifier of the connector.

    * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/ChatSearchResultsEvent.java b/src/main/java/com/cohere/api/types/ChatSearchResultsEvent.java index af1f209..b234bc6 100644 --- a/src/main/java/com/cohere/api/types/ChatSearchResultsEvent.java +++ b/src/main/java/com/cohere/api/types/ChatSearchResultsEvent.java @@ -98,9 +98,6 @@ public Builder from(ChatSearchResultsEvent other) { return this; } - /** - *

    Conducted searches and the ids of documents retrieved from each of them.

    - */ @JsonSetter(value = "search_results", nulls = Nulls.SKIP) public Builder searchResults(Optional> searchResults) { this.searchResults = searchResults; @@ -112,9 +109,6 @@ public Builder searchResults(List searchResults) { return this; } - /** - *

    Documents fetched from searches or provided by the user.

    - */ @JsonSetter(value = "documents", nulls = Nulls.SKIP) public Builder documents(Optional>> documents) { this.documents = documents; diff --git a/src/main/java/com/cohere/api/types/ChatStreamEndEvent.java b/src/main/java/com/cohere/api/types/ChatStreamEndEvent.java index 883c5e6..d0d59d0 100644 --- a/src/main/java/com/cohere/api/types/ChatStreamEndEvent.java +++ b/src/main/java/com/cohere/api/types/ChatStreamEndEvent.java @@ -86,24 +86,12 @@ public static FinishReasonStage builder() { } public interface FinishReasonStage { - /** - *
      - *
    • COMPLETE - the model sent back a finished reply
    • - *
    • ERROR_LIMIT - the reply was cut off because the model reached the maximum number of tokens for its context length
    • - *
    • MAX_TOKENS - the reply was cut off because the model reached the maximum number of tokens specified by the max_tokens parameter
    • - *
    • ERROR - something went wrong when generating the reply
    • - *
    • ERROR_TOXIC - the model generated a reply that was deemed toxic
    • - *
    - */ ResponseStage finishReason(@NotNull ChatStreamEndEventFinishReason finishReason); Builder from(ChatStreamEndEvent other); } public interface ResponseStage { - /** - *

    The consolidated response from the model. Contains the generated reply and all the other information streamed back in the previous events.

    - */ _FinalStage response(@NotNull NonStreamedChatResponse response); } @@ -130,13 +118,6 @@ public Builder from(ChatStreamEndEvent other) { } /** - *
      - *
    • COMPLETE - the model sent back a finished reply
    • - *
    • ERROR_LIMIT - the reply was cut off because the model reached the maximum number of tokens for its context length
    • - *
    • MAX_TOKENS - the reply was cut off because the model reached the maximum number of tokens specified by the max_tokens parameter
    • - *
    • ERROR - something went wrong when generating the reply
    • - *
    • ERROR_TOXIC - the model generated a reply that was deemed toxic
    • - *
    *
      *
    • COMPLETE - the model sent back a finished reply
    • *
    • ERROR_LIMIT - the reply was cut off because the model reached the maximum number of tokens for its context length
    • @@ -154,7 +135,6 @@ public ResponseStage finishReason(@NotNull ChatStreamEndEventFinishReason finish } /** - *

      The consolidated response from the model. Contains the generated reply and all the other information streamed back in the previous events.

      *

      The consolidated response from the model. Contains the generated reply and all the other information streamed back in the previous events.

      * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/ChatStreamStartEvent.java b/src/main/java/com/cohere/api/types/ChatStreamStartEvent.java index c7741d5..0a17271 100644 --- a/src/main/java/com/cohere/api/types/ChatStreamStartEvent.java +++ b/src/main/java/com/cohere/api/types/ChatStreamStartEvent.java @@ -66,9 +66,6 @@ public static GenerationIdStage builder() { } public interface GenerationIdStage { - /** - *

      Unique identifier for the generated reply. Useful for submitting feedback.

      - */ _FinalStage generationId(@NotNull String generationId); Builder from(ChatStreamStartEvent other); @@ -94,7 +91,6 @@ public Builder from(ChatStreamStartEvent other) { } /** - *

      Unique identifier for the generated reply. Useful for submitting feedback.

      *

      Unique identifier for the generated reply. Useful for submitting feedback.

      * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/ChatTextGenerationEvent.java b/src/main/java/com/cohere/api/types/ChatTextGenerationEvent.java index d7c5ef6..639e181 100644 --- a/src/main/java/com/cohere/api/types/ChatTextGenerationEvent.java +++ b/src/main/java/com/cohere/api/types/ChatTextGenerationEvent.java @@ -66,9 +66,6 @@ public static TextStage builder() { } public interface TextStage { - /** - *

      The next batch of text generated by the model.

      - */ _FinalStage text(@NotNull String text); Builder from(ChatTextGenerationEvent other); @@ -94,7 +91,6 @@ public Builder from(ChatTextGenerationEvent other) { } /** - *

      The next batch of text generated by the model.

      *

      The next batch of text generated by the model.

      * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/ChatThinkingContent.java b/src/main/java/com/cohere/api/types/ChatThinkingContent.java new file mode 100644 index 0000000..0021223 --- /dev/null +++ b/src/main/java/com/cohere/api/types/ChatThinkingContent.java @@ -0,0 +1,102 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ChatThinkingContent.Builder.class) +public final class ChatThinkingContent { + private final String thinking; + + private final Map additionalProperties; + + private ChatThinkingContent(String thinking, Map additionalProperties) { + this.thinking = thinking; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("thinking") + public String getThinking() { + return thinking; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ChatThinkingContent && equalTo((ChatThinkingContent) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ChatThinkingContent other) { + return thinking.equals(other.thinking); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.thinking); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ThinkingStage builder() { + return new Builder(); + } + + public interface ThinkingStage { + _FinalStage thinking(@NotNull String thinking); + + Builder from(ChatThinkingContent other); + } + + public interface _FinalStage { + ChatThinkingContent build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements ThinkingStage, _FinalStage { + private String thinking; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ChatThinkingContent other) { + thinking(other.getThinking()); + return this; + } + + @java.lang.Override + @JsonSetter("thinking") + public _FinalStage thinking(@NotNull String thinking) { + this.thinking = Objects.requireNonNull(thinking, "thinking must not be null"); + return this; + } + + @java.lang.Override + public ChatThinkingContent build() { + return new ChatThinkingContent(thinking, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/types/ChatToolCallsGenerationEvent.java b/src/main/java/com/cohere/api/types/ChatToolCallsGenerationEvent.java index ebea921..9c203fd 100644 --- a/src/main/java/com/cohere/api/types/ChatToolCallsGenerationEvent.java +++ b/src/main/java/com/cohere/api/types/ChatToolCallsGenerationEvent.java @@ -94,9 +94,6 @@ public Builder from(ChatToolCallsGenerationEvent other) { return this; } - /** - *

      The text generated related to the tool calls generated

      - */ @JsonSetter(value = "text", nulls = Nulls.SKIP) public Builder text(Optional text) { this.text = text; diff --git a/src/main/java/com/cohere/api/types/ChatToolSource.java b/src/main/java/com/cohere/api/types/ChatToolSource.java index d0e0543..fcbdb5e 100644 --- a/src/main/java/com/cohere/api/types/ChatToolSource.java +++ b/src/main/java/com/cohere/api/types/ChatToolSource.java @@ -92,9 +92,6 @@ public Builder from(ChatToolSource other) { return this; } - /** - *

      The unique identifier of the document

      - */ @JsonSetter(value = "id", nulls = Nulls.SKIP) public Builder id(Optional id) { this.id = id; diff --git a/src/main/java/com/cohere/api/types/Citation.java b/src/main/java/com/cohere/api/types/Citation.java index c65f143..17b09cf 100644 --- a/src/main/java/com/cohere/api/types/Citation.java +++ b/src/main/java/com/cohere/api/types/Citation.java @@ -29,6 +29,8 @@ public final class Citation { private final Optional> sources; + private final Optional contentIndex; + private final Optional type; private final Map additionalProperties; @@ -38,12 +40,14 @@ private Citation( Optional end, Optional text, Optional> sources, + Optional contentIndex, Optional type, Map additionalProperties) { this.start = start; this.end = end; this.text = text; this.sources = sources; + this.contentIndex = contentIndex; this.type = type; this.additionalProperties = additionalProperties; } @@ -77,6 +81,14 @@ public Optional> getSources() { return sources; } + /** + * @return Index of the content block in which this citation appears. + */ + @JsonProperty("content_index") + public Optional getContentIndex() { + return contentIndex; + } + @JsonProperty("type") public Optional getType() { return type; @@ -98,12 +110,13 @@ private boolean equalTo(Citation other) { && end.equals(other.end) && text.equals(other.text) && sources.equals(other.sources) + && contentIndex.equals(other.contentIndex) && type.equals(other.type); } @java.lang.Override public int hashCode() { - return Objects.hash(this.start, this.end, this.text, this.sources, this.type); + return Objects.hash(this.start, this.end, this.text, this.sources, this.contentIndex, this.type); } @java.lang.Override @@ -125,6 +138,8 @@ public static final class Builder { private Optional> sources = Optional.empty(); + private Optional contentIndex = Optional.empty(); + private Optional type = Optional.empty(); @JsonAnySetter @@ -137,13 +152,11 @@ public Builder from(Citation other) { end(other.getEnd()); text(other.getText()); sources(other.getSources()); + contentIndex(other.getContentIndex()); type(other.getType()); return this; } - /** - *

      Start index of the cited snippet in the original source text.

      - */ @JsonSetter(value = "start", nulls = Nulls.SKIP) public Builder start(Optional start) { this.start = start; @@ -155,9 +168,6 @@ public Builder start(Integer start) { return this; } - /** - *

      End index of the cited snippet in the original source text.

      - */ @JsonSetter(value = "end", nulls = Nulls.SKIP) public Builder end(Optional end) { this.end = end; @@ -169,9 +179,6 @@ public Builder end(Integer end) { return this; } - /** - *

      Text snippet that is being cited.

      - */ @JsonSetter(value = "text", nulls = Nulls.SKIP) public Builder text(Optional text) { this.text = text; @@ -194,6 +201,17 @@ public Builder sources(List sources) { return this; } + @JsonSetter(value = "content_index", nulls = Nulls.SKIP) + public Builder contentIndex(Optional contentIndex) { + this.contentIndex = contentIndex; + return this; + } + + public Builder contentIndex(Integer contentIndex) { + this.contentIndex = Optional.ofNullable(contentIndex); + return this; + } + @JsonSetter(value = "type", nulls = Nulls.SKIP) public Builder type(Optional type) { this.type = type; @@ -206,7 +224,7 @@ public Builder type(CitationType type) { } public Citation build() { - return new Citation(start, end, text, sources, type, additionalProperties); + return new Citation(start, end, text, sources, contentIndex, type, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/types/CitationOptions.java b/src/main/java/com/cohere/api/types/CitationOptions.java index f6f2ade..594053f 100644 --- a/src/main/java/com/cohere/api/types/CitationOptions.java +++ b/src/main/java/com/cohere/api/types/CitationOptions.java @@ -82,11 +82,6 @@ public Builder from(CitationOptions other) { return this; } - /** - *

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

      - *

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

      - */ @JsonSetter(value = "mode", nulls = Nulls.SKIP) public Builder mode(Optional mode) { this.mode = mode; diff --git a/src/main/java/com/cohere/api/types/CitationType.java b/src/main/java/com/cohere/api/types/CitationType.java index b08618a..1498629 100644 --- a/src/main/java/com/cohere/api/types/CitationType.java +++ b/src/main/java/com/cohere/api/types/CitationType.java @@ -8,6 +8,8 @@ public enum CitationType { TEXT_CONTENT("TEXT_CONTENT"), + THINKING_CONTENT("THINKING_CONTENT"), + PLAN("PLAN"); private final String value; diff --git a/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItem.java b/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItem.java index b697dae..3d7e57a 100644 --- a/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItem.java +++ b/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItem.java @@ -176,9 +176,6 @@ public interface IdStage { } public interface ClassificationTypeStage { - /** - *

      The type of classification performed

      - */ _FinalStage classificationType( @NotNull ClassifyResponseClassificationsItemClassificationType classificationType); } @@ -186,48 +183,30 @@ _FinalStage classificationType( public interface _FinalStage { ClassifyResponseClassificationsItem build(); - /** - *

      The input text that was classified

      - */ _FinalStage input(Optional input); _FinalStage input(String input); - /** - *

      The predicted label for the associated query (only filled for single-label models)

      - */ _FinalStage prediction(Optional prediction); _FinalStage prediction(String prediction); - /** - *

      An array containing the predicted labels for the associated query (only filled for single-label classification)

      - */ _FinalStage predictions(List predictions); _FinalStage addPredictions(String predictions); _FinalStage addAllPredictions(List predictions); - /** - *

      The confidence score for the top predicted class (only filled for single-label classification)

      - */ _FinalStage confidence(Optional confidence); _FinalStage confidence(Float confidence); - /** - *

      An array containing the confidence scores of all the predictions in the same order

      - */ _FinalStage confidences(List confidences); _FinalStage addConfidences(Float confidences); _FinalStage addAllConfidences(List confidences); - /** - *

      A map containing each label and its confidence score according to the classifier. All the confidence scores add up to 1 for single-label classification. For multi-label classification the label confidences are independent of each other, so they don't have to sum up to 1.

      - */ _FinalStage labels(Map labels); _FinalStage putAllLabels(Map labels); @@ -279,7 +258,6 @@ public ClassificationTypeStage id(@NotNull String id) { } /** - *

      The type of classification performed

      *

      The type of classification performed

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -311,9 +289,6 @@ public _FinalStage putAllLabels(MapA map containing each label and its confidence score according to the classifier. All the confidence scores add up to 1 for single-label classification. For multi-label classification the label confidences are independent of each other, so they don't have to sum up to 1.

      - */ @java.lang.Override @JsonSetter(value = "labels", nulls = Nulls.SKIP) public _FinalStage labels(Map labels) { @@ -342,9 +317,6 @@ public _FinalStage addConfidences(Float confidences) { return this; } - /** - *

      An array containing the confidence scores of all the predictions in the same order

      - */ @java.lang.Override @JsonSetter(value = "confidences", nulls = Nulls.SKIP) public _FinalStage confidences(List confidences) { @@ -363,9 +335,6 @@ public _FinalStage confidence(Float confidence) { return this; } - /** - *

      The confidence score for the top predicted class (only filled for single-label classification)

      - */ @java.lang.Override @JsonSetter(value = "confidence", nulls = Nulls.SKIP) public _FinalStage confidence(Optional confidence) { @@ -393,9 +362,6 @@ public _FinalStage addPredictions(String predictions) { return this; } - /** - *

      An array containing the predicted labels for the associated query (only filled for single-label classification)

      - */ @java.lang.Override @JsonSetter(value = "predictions", nulls = Nulls.SKIP) public _FinalStage predictions(List predictions) { @@ -414,9 +380,6 @@ public _FinalStage prediction(String prediction) { return this; } - /** - *

      The predicted label for the associated query (only filled for single-label models)

      - */ @java.lang.Override @JsonSetter(value = "prediction", nulls = Nulls.SKIP) public _FinalStage prediction(Optional prediction) { @@ -434,9 +397,6 @@ public _FinalStage input(String input) { return this; } - /** - *

      The input text that was classified

      - */ @java.lang.Override @JsonSetter(value = "input", nulls = Nulls.SKIP) public _FinalStage input(Optional input) { diff --git a/src/main/java/com/cohere/api/types/Connector.java b/src/main/java/com/cohere/api/types/Connector.java index d230735..51a9b13 100644 --- a/src/main/java/com/cohere/api/types/Connector.java +++ b/src/main/java/com/cohere/api/types/Connector.java @@ -243,99 +243,58 @@ public static IdStage builder() { } public interface IdStage { - /** - *

      The unique identifier of the connector (used in both /connectors & /chat endpoints). - * This is automatically created from the name of the connector upon registration.

      - */ NameStage id(@NotNull String id); Builder from(Connector other); } public interface NameStage { - /** - *

      A human-readable name for the connector.

      - */ CreatedAtStage name(@NotNull String name); } public interface CreatedAtStage { - /** - *

      The UTC time at which the connector was created.

      - */ UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt); } public interface UpdatedAtStage { - /** - *

      The UTC time at which the connector was last updated.

      - */ _FinalStage updatedAt(@NotNull OffsetDateTime updatedAt); } public interface _FinalStage { Connector build(); - /** - *

      The organization to which this connector belongs. This is automatically set to - * the organization of the user who created the connector.

      - */ _FinalStage organizationId(Optional organizationId); _FinalStage organizationId(String organizationId); - /** - *

      A description of the connector.

      - */ _FinalStage description(Optional description); _FinalStage description(String description); - /** - *

      The URL of the connector that will be used to search for documents.

      - */ _FinalStage url(Optional url); _FinalStage url(String url); - /** - *

      A list of fields to exclude from the prompt (fields remain in the document).

      - */ _FinalStage excludes(Optional> excludes); _FinalStage excludes(List excludes); - /** - *

      The type of authentication/authorization used by the connector. Possible values: [oauth, service_auth]

      - */ _FinalStage authType(Optional authType); _FinalStage authType(String authType); - /** - *

      The OAuth 2.0 configuration for the connector.

      - */ _FinalStage oauth(Optional oauth); _FinalStage oauth(ConnectorOAuth oauth); - /** - *

      The OAuth status for the user making the request. One of ["valid", "expired", ""]. Empty string (field is omitted) means the user has not authorized the connector yet.

      - */ _FinalStage authStatus(Optional authStatus); _FinalStage authStatus(ConnectorAuthStatus authStatus); - /** - *

      Whether the connector is active or not.

      - */ _FinalStage active(Optional active); _FinalStage active(Boolean active); - /** - *

      Whether a chat request should continue or not if the request to this connector fails.

      - */ _FinalStage continueOnFailure(Optional continueOnFailure); _FinalStage continueOnFailure(Boolean continueOnFailure); @@ -393,8 +352,6 @@ public Builder from(Connector other) { } /** - *

      The unique identifier of the connector (used in both /connectors & /chat endpoints). - * This is automatically created from the name of the connector upon registration.

      *

      The unique identifier of the connector (used in both /connectors & /chat endpoints). * This is automatically created from the name of the connector upon registration.

      * @return Reference to {@code this} so that method calls can be chained together. @@ -407,7 +364,6 @@ public NameStage id(@NotNull String id) { } /** - *

      A human-readable name for the connector.

      *

      A human-readable name for the connector.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -419,7 +375,6 @@ public CreatedAtStage name(@NotNull String name) { } /** - *

      The UTC time at which the connector was created.

      *

      The UTC time at which the connector was created.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -431,7 +386,6 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { } /** - *

      The UTC time at which the connector was last updated.

      *

      The UTC time at which the connector was last updated.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -452,9 +406,6 @@ public _FinalStage continueOnFailure(Boolean continueOnFailure) { return this; } - /** - *

      Whether a chat request should continue or not if the request to this connector fails.

      - */ @java.lang.Override @JsonSetter(value = "continue_on_failure", nulls = Nulls.SKIP) public _FinalStage continueOnFailure(Optional continueOnFailure) { @@ -472,9 +423,6 @@ public _FinalStage active(Boolean active) { return this; } - /** - *

      Whether the connector is active or not.

      - */ @java.lang.Override @JsonSetter(value = "active", nulls = Nulls.SKIP) public _FinalStage active(Optional active) { @@ -492,9 +440,6 @@ public _FinalStage authStatus(ConnectorAuthStatus authStatus) { return this; } - /** - *

      The OAuth status for the user making the request. One of ["valid", "expired", ""]. Empty string (field is omitted) means the user has not authorized the connector yet.

      - */ @java.lang.Override @JsonSetter(value = "auth_status", nulls = Nulls.SKIP) public _FinalStage authStatus(Optional authStatus) { @@ -512,9 +457,6 @@ public _FinalStage oauth(ConnectorOAuth oauth) { return this; } - /** - *

      The OAuth 2.0 configuration for the connector.

      - */ @java.lang.Override @JsonSetter(value = "oauth", nulls = Nulls.SKIP) public _FinalStage oauth(Optional oauth) { @@ -532,9 +474,6 @@ public _FinalStage authType(String authType) { return this; } - /** - *

      The type of authentication/authorization used by the connector. Possible values: [oauth, service_auth]

      - */ @java.lang.Override @JsonSetter(value = "auth_type", nulls = Nulls.SKIP) public _FinalStage authType(Optional authType) { @@ -552,9 +491,6 @@ public _FinalStage excludes(List excludes) { return this; } - /** - *

      A list of fields to exclude from the prompt (fields remain in the document).

      - */ @java.lang.Override @JsonSetter(value = "excludes", nulls = Nulls.SKIP) public _FinalStage excludes(Optional> excludes) { @@ -572,9 +508,6 @@ public _FinalStage url(String url) { return this; } - /** - *

      The URL of the connector that will be used to search for documents.

      - */ @java.lang.Override @JsonSetter(value = "url", nulls = Nulls.SKIP) public _FinalStage url(Optional url) { @@ -592,9 +525,6 @@ public _FinalStage description(String description) { return this; } - /** - *

      A description of the connector.

      - */ @java.lang.Override @JsonSetter(value = "description", nulls = Nulls.SKIP) public _FinalStage description(Optional description) { @@ -613,10 +543,6 @@ public _FinalStage organizationId(String organizationId) { return this; } - /** - *

      The organization to which this connector belongs. This is automatically set to - * the organization of the user who created the connector.

      - */ @java.lang.Override @JsonSetter(value = "organization_id", nulls = Nulls.SKIP) public _FinalStage organizationId(Optional organizationId) { diff --git a/src/main/java/com/cohere/api/types/ConnectorOAuth.java b/src/main/java/com/cohere/api/types/ConnectorOAuth.java index 7f64f47..a1a9d6a 100644 --- a/src/main/java/com/cohere/api/types/ConnectorOAuth.java +++ b/src/main/java/com/cohere/api/types/ConnectorOAuth.java @@ -122,41 +122,26 @@ public static AuthorizeUrlStage builder() { } public interface AuthorizeUrlStage { - /** - *

      The OAuth 2.0 /authorize endpoint to use when users authorize the connector.

      - */ TokenUrlStage authorizeUrl(@NotNull String authorizeUrl); Builder from(ConnectorOAuth other); } public interface TokenUrlStage { - /** - *

      The OAuth 2.0 /token endpoint to use when users authorize the connector.

      - */ _FinalStage tokenUrl(@NotNull String tokenUrl); } public interface _FinalStage { ConnectorOAuth build(); - /** - *

      The OAuth 2.0 client ID. This field is encrypted at rest.

      - */ _FinalStage clientId(Optional clientId); _FinalStage clientId(String clientId); - /** - *

      The OAuth 2.0 client Secret. This field is encrypted at rest and never returned in a response.

      - */ _FinalStage clientSecret(Optional clientSecret); _FinalStage clientSecret(String clientSecret); - /** - *

      The OAuth scopes to request when users authorize the connector.

      - */ _FinalStage scope(Optional scope); _FinalStage scope(String scope); @@ -190,7 +175,6 @@ public Builder from(ConnectorOAuth other) { } /** - *

      The OAuth 2.0 /authorize endpoint to use when users authorize the connector.

      *

      The OAuth 2.0 /authorize endpoint to use when users authorize the connector.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -202,7 +186,6 @@ public TokenUrlStage authorizeUrl(@NotNull String authorizeUrl) { } /** - *

      The OAuth 2.0 /token endpoint to use when users authorize the connector.

      *

      The OAuth 2.0 /token endpoint to use when users authorize the connector.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -223,9 +206,6 @@ public _FinalStage scope(String scope) { return this; } - /** - *

      The OAuth scopes to request when users authorize the connector.

      - */ @java.lang.Override @JsonSetter(value = "scope", nulls = Nulls.SKIP) public _FinalStage scope(Optional scope) { @@ -243,9 +223,6 @@ public _FinalStage clientSecret(String clientSecret) { return this; } - /** - *

      The OAuth 2.0 client Secret. This field is encrypted at rest and never returned in a response.

      - */ @java.lang.Override @JsonSetter(value = "client_secret", nulls = Nulls.SKIP) public _FinalStage clientSecret(Optional clientSecret) { @@ -263,9 +240,6 @@ public _FinalStage clientId(String clientId) { return this; } - /** - *

      The OAuth 2.0 client ID. This field is encrypted at rest.

      - */ @java.lang.Override @JsonSetter(value = "client_id", nulls = Nulls.SKIP) public _FinalStage clientId(Optional clientId) { diff --git a/src/main/java/com/cohere/api/types/Content.java b/src/main/java/com/cohere/api/types/Content.java index 1e60710..1f791f8 100644 --- a/src/main/java/com/cohere/api/types/Content.java +++ b/src/main/java/com/cohere/api/types/Content.java @@ -88,7 +88,6 @@ private interface Value { } @JsonTypeName("text") - @JsonIgnoreProperties("type") private static final class TextValue implements Value { @JsonUnwrapped private ChatTextContent value; @@ -127,7 +126,6 @@ public String toString() { } @JsonTypeName("image_url") - @JsonIgnoreProperties("type") private static final class ImageUrlValue implements Value { @JsonUnwrapped private ImageContent value; @@ -165,7 +163,6 @@ public String toString() { } } - @JsonIgnoreProperties("type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/CreateConnectorOAuth.java b/src/main/java/com/cohere/api/types/CreateConnectorOAuth.java index 35ff4bb..fe2cd58 100644 --- a/src/main/java/com/cohere/api/types/CreateConnectorOAuth.java +++ b/src/main/java/com/cohere/api/types/CreateConnectorOAuth.java @@ -146,9 +146,6 @@ public Builder from(CreateConnectorOAuth other) { return this; } - /** - *

      The OAuth 2.0 client ID. This fields is encrypted at rest.

      - */ @JsonSetter(value = "client_id", nulls = Nulls.SKIP) public Builder clientId(Optional clientId) { this.clientId = clientId; @@ -160,9 +157,6 @@ public Builder clientId(String clientId) { return this; } - /** - *

      The OAuth 2.0 client Secret. This field is encrypted at rest and never returned in a response.

      - */ @JsonSetter(value = "client_secret", nulls = Nulls.SKIP) public Builder clientSecret(Optional clientSecret) { this.clientSecret = clientSecret; @@ -174,9 +168,6 @@ public Builder clientSecret(String clientSecret) { return this; } - /** - *

      The OAuth 2.0 /authorize endpoint to use when users authorize the connector.

      - */ @JsonSetter(value = "authorize_url", nulls = Nulls.SKIP) public Builder authorizeUrl(Optional authorizeUrl) { this.authorizeUrl = authorizeUrl; @@ -188,9 +179,6 @@ public Builder authorizeUrl(String authorizeUrl) { return this; } - /** - *

      The OAuth 2.0 /token endpoint to use when users authorize the connector.

      - */ @JsonSetter(value = "token_url", nulls = Nulls.SKIP) public Builder tokenUrl(Optional tokenUrl) { this.tokenUrl = tokenUrl; @@ -202,9 +190,6 @@ public Builder tokenUrl(String tokenUrl) { return this; } - /** - *

      The OAuth scopes to request when users authorize the connector.

      - */ @JsonSetter(value = "scope", nulls = Nulls.SKIP) public Builder scope(Optional scope) { this.scope = scope; diff --git a/src/main/java/com/cohere/api/types/CreateConnectorServiceAuth.java b/src/main/java/com/cohere/api/types/CreateConnectorServiceAuth.java index 7a08882..11f7820 100644 --- a/src/main/java/com/cohere/api/types/CreateConnectorServiceAuth.java +++ b/src/main/java/com/cohere/api/types/CreateConnectorServiceAuth.java @@ -80,9 +80,6 @@ public interface TypeStage { } public interface TokenStage { - /** - *

      The token that will be used in the HTTP Authorization header when making requests to the connector. This field is encrypted at rest and never returned in a response.

      - */ _FinalStage token(@NotNull String token); } @@ -116,7 +113,6 @@ public TokenStage type(@NotNull AuthTokenType type) { } /** - *

      The token that will be used in the HTTP Authorization header when making requests to the connector. This field is encrypted at rest and never returned in a response.

      *

      The token that will be used in the HTTP Authorization header when making requests to the connector. This field is encrypted at rest and never returned in a response.

      * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/Dataset.java b/src/main/java/com/cohere/api/types/Dataset.java index 4a166d2..7560d80 100644 --- a/src/main/java/com/cohere/api/types/Dataset.java +++ b/src/main/java/com/cohere/api/types/Dataset.java @@ -215,32 +215,20 @@ public static IdStage builder() { } public interface IdStage { - /** - *

      The dataset ID

      - */ NameStage id(@NotNull String id); Builder from(Dataset other); } public interface NameStage { - /** - *

      The name of the dataset

      - */ CreatedAtStage name(@NotNull String name); } public interface CreatedAtStage { - /** - *

      The creation date

      - */ UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt); } public interface UpdatedAtStage { - /** - *

      The last update date

      - */ DatasetTypeStage updatedAt(@NotNull OffsetDateTime updatedAt); } @@ -255,16 +243,10 @@ public interface ValidationStatusStage { public interface _FinalStage { Dataset build(); - /** - *

      Errors found during validation

      - */ _FinalStage validationError(Optional validationError); _FinalStage validationError(String validationError); - /** - *

      the avro schema of the dataset

      - */ _FinalStage schema(Optional schema); _FinalStage schema(String schema); @@ -277,16 +259,10 @@ public interface _FinalStage { _FinalStage preserveFields(List preserveFields); - /** - *

      the underlying files that make up the dataset

      - */ _FinalStage datasetParts(Optional> datasetParts); _FinalStage datasetParts(List datasetParts); - /** - *

      warnings found during validation

      - */ _FinalStage validationWarnings(Optional> validationWarnings); _FinalStage validationWarnings(List validationWarnings); @@ -348,7 +324,6 @@ public Builder from(Dataset other) { } /** - *

      The dataset ID

      *

      The dataset ID

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -360,7 +335,6 @@ public NameStage id(@NotNull String id) { } /** - *

      The name of the dataset

      *

      The name of the dataset

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -372,7 +346,6 @@ public CreatedAtStage name(@NotNull String name) { } /** - *

      The creation date

      *

      The creation date

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -384,7 +357,6 @@ public UpdatedAtStage createdAt(@NotNull OffsetDateTime createdAt) { } /** - *

      The last update date

      *

      The last update date

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -419,9 +391,6 @@ public _FinalStage validationWarnings(List validationWarnings) { return this; } - /** - *

      warnings found during validation

      - */ @java.lang.Override @JsonSetter(value = "validation_warnings", nulls = Nulls.SKIP) public _FinalStage validationWarnings(Optional> validationWarnings) { @@ -439,9 +408,6 @@ public _FinalStage datasetParts(List datasetParts) { return this; } - /** - *

      the underlying files that make up the dataset

      - */ @java.lang.Override @JsonSetter(value = "dataset_parts", nulls = Nulls.SKIP) public _FinalStage datasetParts(Optional> datasetParts) { @@ -485,9 +451,6 @@ public _FinalStage schema(String schema) { return this; } - /** - *

      the avro schema of the dataset

      - */ @java.lang.Override @JsonSetter(value = "schema", nulls = Nulls.SKIP) public _FinalStage schema(Optional schema) { @@ -505,9 +468,6 @@ public _FinalStage validationError(String validationError) { return this; } - /** - *

      Errors found during validation

      - */ @java.lang.Override @JsonSetter(value = "validation_error", nulls = Nulls.SKIP) public _FinalStage validationError(Optional validationError) { diff --git a/src/main/java/com/cohere/api/types/DatasetPart.java b/src/main/java/com/cohere/api/types/DatasetPart.java index fa05ba5..d44a278 100644 --- a/src/main/java/com/cohere/api/types/DatasetPart.java +++ b/src/main/java/com/cohere/api/types/DatasetPart.java @@ -163,62 +163,38 @@ public static IdStage builder() { } public interface IdStage { - /** - *

      The dataset part ID

      - */ NameStage id(@NotNull String id); Builder from(DatasetPart other); } public interface NameStage { - /** - *

      The name of the dataset part

      - */ _FinalStage name(@NotNull String name); } public interface _FinalStage { DatasetPart build(); - /** - *

      The download url of the file

      - */ _FinalStage url(Optional url); _FinalStage url(String url); - /** - *

      The index of the file

      - */ _FinalStage index(Optional index); _FinalStage index(Integer index); - /** - *

      The size of the file in bytes

      - */ _FinalStage sizeBytes(Optional sizeBytes); _FinalStage sizeBytes(Integer sizeBytes); - /** - *

      The number of rows in the file

      - */ _FinalStage numRows(Optional numRows); _FinalStage numRows(Integer numRows); - /** - *

      The download url of the original file

      - */ _FinalStage originalUrl(Optional originalUrl); _FinalStage originalUrl(String originalUrl); - /** - *

      The first few rows of the parsed file

      - */ _FinalStage samples(Optional> samples); _FinalStage samples(List samples); @@ -261,7 +237,6 @@ public Builder from(DatasetPart other) { } /** - *

      The dataset part ID

      *

      The dataset part ID

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -273,7 +248,6 @@ public NameStage id(@NotNull String id) { } /** - *

      The name of the dataset part

      *

      The name of the dataset part

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -294,9 +268,6 @@ public _FinalStage samples(List samples) { return this; } - /** - *

      The first few rows of the parsed file

      - */ @java.lang.Override @JsonSetter(value = "samples", nulls = Nulls.SKIP) public _FinalStage samples(Optional> samples) { @@ -314,9 +285,6 @@ public _FinalStage originalUrl(String originalUrl) { return this; } - /** - *

      The download url of the original file

      - */ @java.lang.Override @JsonSetter(value = "original_url", nulls = Nulls.SKIP) public _FinalStage originalUrl(Optional originalUrl) { @@ -334,9 +302,6 @@ public _FinalStage numRows(Integer numRows) { return this; } - /** - *

      The number of rows in the file

      - */ @java.lang.Override @JsonSetter(value = "num_rows", nulls = Nulls.SKIP) public _FinalStage numRows(Optional numRows) { @@ -354,9 +319,6 @@ public _FinalStage sizeBytes(Integer sizeBytes) { return this; } - /** - *

      The size of the file in bytes

      - */ @java.lang.Override @JsonSetter(value = "size_bytes", nulls = Nulls.SKIP) public _FinalStage sizeBytes(Optional sizeBytes) { @@ -374,9 +336,6 @@ public _FinalStage index(Integer index) { return this; } - /** - *

      The index of the file

      - */ @java.lang.Override @JsonSetter(value = "index", nulls = Nulls.SKIP) public _FinalStage index(Optional index) { @@ -394,9 +353,6 @@ public _FinalStage url(String url) { return this; } - /** - *

      The download url of the file

      - */ @java.lang.Override @JsonSetter(value = "url", nulls = Nulls.SKIP) public _FinalStage url(Optional url) { diff --git a/src/main/java/com/cohere/api/types/DetokenizeResponse.java b/src/main/java/com/cohere/api/types/DetokenizeResponse.java index 3bb0fd9..98e1517 100644 --- a/src/main/java/com/cohere/api/types/DetokenizeResponse.java +++ b/src/main/java/com/cohere/api/types/DetokenizeResponse.java @@ -76,9 +76,6 @@ public static TextStage builder() { } public interface TextStage { - /** - *

      A string representing the list of tokens.

      - */ _FinalStage text(@NotNull String text); Builder from(DetokenizeResponse other); @@ -111,7 +108,6 @@ public Builder from(DetokenizeResponse other) { } /** - *

      A string representing the list of tokens.

      *

      A string representing the list of tokens.

      * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/Document.java b/src/main/java/com/cohere/api/types/Document.java index 07e618d..90929df 100644 --- a/src/main/java/com/cohere/api/types/Document.java +++ b/src/main/java/com/cohere/api/types/Document.java @@ -95,9 +95,6 @@ public Builder from(Document other) { return this; } - /** - *

      A relevant document that the model can cite to generate a more accurate reply. Each document is a string-any dictionary.

      - */ @JsonSetter(value = "data", nulls = Nulls.SKIP) public Builder data(Map data) { this.data.clear(); @@ -115,9 +112,6 @@ public Builder data(String key, Object value) { return this; } - /** - *

      Unique identifier for this document which will be referenced in citations. If not provided an ID will be automatically generated.

      - */ @JsonSetter(value = "id", nulls = Nulls.SKIP) public Builder id(Optional id) { this.id = id; diff --git a/src/main/java/com/cohere/api/types/EmbedByTypeResponse.java b/src/main/java/com/cohere/api/types/EmbedByTypeResponse.java index 55f2169..b3ba75e 100644 --- a/src/main/java/com/cohere/api/types/EmbedByTypeResponse.java +++ b/src/main/java/com/cohere/api/types/EmbedByTypeResponse.java @@ -123,25 +123,16 @@ public interface IdStage { } public interface EmbeddingsStage { - /** - *

      An object with different embedding types. The length of each embedding type array will be the same as the length of the original texts array.

      - */ _FinalStage embeddings(@NotNull EmbedByTypeResponseEmbeddings embeddings); } public interface _FinalStage { EmbedByTypeResponse build(); - /** - *

      The text entries for which embeddings were returned.

      - */ _FinalStage texts(Optional> texts); _FinalStage texts(List texts); - /** - *

      The image entries for which embeddings were returned.

      - */ _FinalStage images(Optional> images); _FinalStage images(List images); @@ -186,7 +177,6 @@ public EmbeddingsStage id(@NotNull String id) { } /** - *

      An object with different embedding types. The length of each embedding type array will be the same as the length of the original texts array.

      *

      An object with different embedding types. The length of each embedding type array will be the same as the length of the original texts array.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -220,9 +210,6 @@ public _FinalStage images(List images) { return this; } - /** - *

      The image entries for which embeddings were returned.

      - */ @java.lang.Override @JsonSetter(value = "images", nulls = Nulls.SKIP) public _FinalStage images(Optional> images) { @@ -240,9 +227,6 @@ public _FinalStage texts(List texts) { return this; } - /** - *

      The text entries for which embeddings were returned.

      - */ @java.lang.Override @JsonSetter(value = "texts", nulls = Nulls.SKIP) public _FinalStage texts(Optional> texts) { diff --git a/src/main/java/com/cohere/api/types/EmbedByTypeResponseEmbeddings.java b/src/main/java/com/cohere/api/types/EmbedByTypeResponseEmbeddings.java index 843f74f..e89db8f 100644 --- a/src/main/java/com/cohere/api/types/EmbedByTypeResponseEmbeddings.java +++ b/src/main/java/com/cohere/api/types/EmbedByTypeResponseEmbeddings.java @@ -147,9 +147,6 @@ public Builder from(EmbedByTypeResponseEmbeddings other) { return this; } - /** - *

      An array of float embeddings.

      - */ @JsonSetter(value = "float", nulls = Nulls.SKIP) public Builder float_(Optional>> float_) { this.float_ = float_; @@ -161,9 +158,6 @@ public Builder float_(List> float_) { return this; } - /** - *

      An array of signed int8 embeddings. Each value is between -128 and 127.

      - */ @JsonSetter(value = "int8", nulls = Nulls.SKIP) public Builder int8(Optional>> int8) { this.int8 = int8; @@ -175,9 +169,6 @@ public Builder int8(List> int8) { return this; } - /** - *

      An array of unsigned int8 embeddings. Each value is between 0 and 255.

      - */ @JsonSetter(value = "uint8", nulls = Nulls.SKIP) public Builder uint8(Optional>> uint8) { this.uint8 = uint8; @@ -189,9 +180,6 @@ public Builder uint8(List> uint8) { return this; } - /** - *

      An array of packed signed binary embeddings. The length of each binary embedding is 1/8 the length of the float embeddings of the provided model. Each value is between -128 and 127.

      - */ @JsonSetter(value = "binary", nulls = Nulls.SKIP) public Builder binary(Optional>> binary) { this.binary = binary; @@ -203,9 +191,6 @@ public Builder binary(List> binary) { return this; } - /** - *

      An array of packed unsigned binary embeddings. The length of each binary embedding is 1/8 the length of the float embeddings of the provided model. Each value is between 0 and 255.

      - */ @JsonSetter(value = "ubinary", nulls = Nulls.SKIP) public Builder ubinary(Optional>> ubinary) { this.ubinary = ubinary; diff --git a/src/main/java/com/cohere/api/types/EmbedContent.java b/src/main/java/com/cohere/api/types/EmbedContent.java index 7a88285..66a9193 100644 --- a/src/main/java/com/cohere/api/types/EmbedContent.java +++ b/src/main/java/com/cohere/api/types/EmbedContent.java @@ -88,7 +88,6 @@ private interface Value { } @JsonTypeName("image_url") - @JsonIgnoreProperties("type") private static final class ImageUrlValue implements Value { @JsonUnwrapped private EmbedImage value; @@ -127,7 +126,6 @@ public String toString() { } @JsonTypeName("text") - @JsonIgnoreProperties("type") private static final class TextValue implements Value { @JsonUnwrapped private EmbedText value; @@ -165,7 +163,6 @@ public String toString() { } } - @JsonIgnoreProperties("type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/EmbedFloatsResponse.java b/src/main/java/com/cohere/api/types/EmbedFloatsResponse.java index bb95964..21c7b5a 100644 --- a/src/main/java/com/cohere/api/types/EmbedFloatsResponse.java +++ b/src/main/java/com/cohere/api/types/EmbedFloatsResponse.java @@ -126,27 +126,18 @@ public interface IdStage { public interface _FinalStage { EmbedFloatsResponse build(); - /** - *

      An array of embeddings, where each embedding is an array of floats. The length of the embeddings array will be the same as the length of the original texts array.

      - */ _FinalStage embeddings(List> embeddings); _FinalStage addEmbeddings(List embeddings); _FinalStage addAllEmbeddings(List> embeddings); - /** - *

      The text entries for which embeddings were returned.

      - */ _FinalStage texts(List texts); _FinalStage addTexts(String texts); _FinalStage addAllTexts(List texts); - /** - *

      The image entries for which embeddings were returned.

      - */ _FinalStage images(Optional> images); _FinalStage images(List images); @@ -213,9 +204,6 @@ public _FinalStage images(List images) { return this; } - /** - *

      The image entries for which embeddings were returned.

      - */ @java.lang.Override @JsonSetter(value = "images", nulls = Nulls.SKIP) public _FinalStage images(Optional> images) { @@ -243,9 +231,6 @@ public _FinalStage addTexts(String texts) { return this; } - /** - *

      The text entries for which embeddings were returned.

      - */ @java.lang.Override @JsonSetter(value = "texts", nulls = Nulls.SKIP) public _FinalStage texts(List texts) { @@ -274,9 +259,6 @@ public _FinalStage addEmbeddings(List embeddings) { return this; } - /** - *

      An array of embeddings, where each embedding is an array of floats. The length of the embeddings array will be the same as the length of the original texts array.

      - */ @java.lang.Override @JsonSetter(value = "embeddings", nulls = Nulls.SKIP) public _FinalStage embeddings(List> embeddings) { diff --git a/src/main/java/com/cohere/api/types/EmbedInput.java b/src/main/java/com/cohere/api/types/EmbedInput.java index 8f4898f..7a18bf3 100644 --- a/src/main/java/com/cohere/api/types/EmbedInput.java +++ b/src/main/java/com/cohere/api/types/EmbedInput.java @@ -81,9 +81,6 @@ public Builder from(EmbedInput other) { return this; } - /** - *

      An array of objects containing the input data for the model to embed.

      - */ @JsonSetter(value = "content", nulls = Nulls.SKIP) public Builder content(List content) { this.content.clear(); diff --git a/src/main/java/com/cohere/api/types/EmbedJob.java b/src/main/java/com/cohere/api/types/EmbedJob.java index 27ff84a..b88d2a6 100644 --- a/src/main/java/com/cohere/api/types/EmbedJob.java +++ b/src/main/java/com/cohere/api/types/EmbedJob.java @@ -181,62 +181,38 @@ public static JobIdStage builder() { } public interface JobIdStage { - /** - *

      ID of the embed job

      - */ StatusStage jobId(@NotNull String jobId); Builder from(EmbedJob other); } public interface StatusStage { - /** - *

      The status of the embed job

      - */ CreatedAtStage status(@NotNull EmbedJobStatus status); } public interface CreatedAtStage { - /** - *

      The creation date of the embed job

      - */ InputDatasetIdStage createdAt(@NotNull OffsetDateTime createdAt); } public interface InputDatasetIdStage { - /** - *

      ID of the input dataset

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

      ID of the model used to embed

      - */ TruncateStage model(@NotNull String model); } public interface TruncateStage { - /** - *

      The truncation option used

      - */ _FinalStage truncate(@NotNull EmbedJobTruncate truncate); } public interface _FinalStage { EmbedJob build(); - /** - *

      The name of the embed job

      - */ _FinalStage name(Optional name); _FinalStage name(String name); - /** - *

      ID of the resulting output dataset

      - */ _FinalStage outputDatasetId(Optional outputDatasetId); _FinalStage outputDatasetId(String outputDatasetId); @@ -293,7 +269,6 @@ public Builder from(EmbedJob other) { } /** - *

      ID of the embed job

      *

      ID of the embed job

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -305,7 +280,6 @@ public StatusStage jobId(@NotNull String jobId) { } /** - *

      The status of the embed job

      *

      The status of the embed job

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -317,7 +291,6 @@ public CreatedAtStage status(@NotNull EmbedJobStatus status) { } /** - *

      The creation date of the embed job

      *

      The creation date of the embed job

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -329,7 +302,6 @@ public InputDatasetIdStage createdAt(@NotNull OffsetDateTime createdAt) { } /** - *

      ID of the input dataset

      *

      ID of the input dataset

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -341,7 +313,6 @@ public ModelStage inputDatasetId(@NotNull String inputDatasetId) { } /** - *

      ID of the model used to embed

      *

      ID of the model used to embed

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -353,7 +324,6 @@ public TruncateStage model(@NotNull String model) { } /** - *

      The truncation option used

      *

      The truncation option used

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -387,9 +357,6 @@ public _FinalStage outputDatasetId(String outputDatasetId) { return this; } - /** - *

      ID of the resulting output dataset

      - */ @java.lang.Override @JsonSetter(value = "output_dataset_id", nulls = Nulls.SKIP) public _FinalStage outputDatasetId(Optional outputDatasetId) { @@ -407,9 +374,6 @@ public _FinalStage name(String name) { return this; } - /** - *

      The name of the embed job

      - */ @java.lang.Override @JsonSetter(value = "name", nulls = Nulls.SKIP) public _FinalStage name(Optional name) { diff --git a/src/main/java/com/cohere/api/types/EmbedResponse.java b/src/main/java/com/cohere/api/types/EmbedResponse.java index 1411636..052ac33 100644 --- a/src/main/java/com/cohere/api/types/EmbedResponse.java +++ b/src/main/java/com/cohere/api/types/EmbedResponse.java @@ -92,7 +92,6 @@ private interface Value { } @JsonTypeName("embeddings_floats") - @JsonIgnoreProperties("response_type") private static final class EmbeddingsFloatsValue implements Value { @JsonUnwrapped private EmbedFloatsResponse value; @@ -131,7 +130,6 @@ public String toString() { } @JsonTypeName("embeddings_by_type") - @JsonIgnoreProperties("response_type") private static final class EmbeddingsByTypeValue implements Value { @JsonUnwrapped private EmbedByTypeResponse value; @@ -169,7 +167,6 @@ public String toString() { } } - @JsonIgnoreProperties("response_type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/FinetuneDatasetMetrics.java b/src/main/java/com/cohere/api/types/FinetuneDatasetMetrics.java index 0925d1c..452ae7f 100644 --- a/src/main/java/com/cohere/api/types/FinetuneDatasetMetrics.java +++ b/src/main/java/com/cohere/api/types/FinetuneDatasetMetrics.java @@ -168,9 +168,6 @@ public Builder from(FinetuneDatasetMetrics other) { return this; } - /** - *

      The number of tokens of valid examples that can be used for training.

      - */ @JsonSetter(value = "trainable_token_count", nulls = Nulls.SKIP) public Builder trainableTokenCount(Optional trainableTokenCount) { this.trainableTokenCount = trainableTokenCount; @@ -182,9 +179,6 @@ public Builder trainableTokenCount(Long trainableTokenCount) { return this; } - /** - *

      The overall number of examples.

      - */ @JsonSetter(value = "total_examples", nulls = Nulls.SKIP) public Builder totalExamples(Optional totalExamples) { this.totalExamples = totalExamples; @@ -196,9 +190,6 @@ public Builder totalExamples(Long totalExamples) { return this; } - /** - *

      The number of training examples.

      - */ @JsonSetter(value = "train_examples", nulls = Nulls.SKIP) public Builder trainExamples(Optional trainExamples) { this.trainExamples = trainExamples; @@ -210,9 +201,6 @@ public Builder trainExamples(Long trainExamples) { return this; } - /** - *

      The size in bytes of all training examples.

      - */ @JsonSetter(value = "train_size_bytes", nulls = Nulls.SKIP) public Builder trainSizeBytes(Optional trainSizeBytes) { this.trainSizeBytes = trainSizeBytes; @@ -224,9 +212,6 @@ public Builder trainSizeBytes(Long trainSizeBytes) { return this; } - /** - *

      Number of evaluation examples.

      - */ @JsonSetter(value = "eval_examples", nulls = Nulls.SKIP) public Builder evalExamples(Optional evalExamples) { this.evalExamples = evalExamples; @@ -238,9 +223,6 @@ public Builder evalExamples(Long evalExamples) { return this; } - /** - *

      The size in bytes of all eval examples.

      - */ @JsonSetter(value = "eval_size_bytes", nulls = Nulls.SKIP) public Builder evalSizeBytes(Optional evalSizeBytes) { this.evalSizeBytes = evalSizeBytes; diff --git a/src/main/java/com/cohere/api/types/GenerateStreamError.java b/src/main/java/com/cohere/api/types/GenerateStreamError.java index 678e4e9..33cf15c 100644 --- a/src/main/java/com/cohere/api/types/GenerateStreamError.java +++ b/src/main/java/com/cohere/api/types/GenerateStreamError.java @@ -113,18 +113,12 @@ public interface FinishReasonStage { } public interface ErrStage { - /** - *

      Error message

      - */ _FinalStage err(@NotNull String err); } public interface _FinalStage { GenerateStreamError build(); - /** - *

      Refers to the nth generation. Only present when num_generations is greater than zero.

      - */ _FinalStage index(Optional index); _FinalStage index(Integer index); @@ -169,7 +163,6 @@ public ErrStage finishReason(@NotNull FinishReason finishReason) { } /** - *

      Error message

      *

      Error message

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -190,9 +183,6 @@ public _FinalStage index(Integer index) { return this; } - /** - *

      Refers to the nth generation. Only present when num_generations is greater than zero.

      - */ @java.lang.Override @JsonSetter(value = "index", nulls = Nulls.SKIP) public _FinalStage index(Optional index) { diff --git a/src/main/java/com/cohere/api/types/GenerateStreamText.java b/src/main/java/com/cohere/api/types/GenerateStreamText.java index 575033e..0a2f01d 100644 --- a/src/main/java/com/cohere/api/types/GenerateStreamText.java +++ b/src/main/java/com/cohere/api/types/GenerateStreamText.java @@ -88,9 +88,6 @@ public static TextStage builder() { } public interface TextStage { - /** - *

      A segment of text of the generation.

      - */ IsFinishedStage text(@NotNull String text); Builder from(GenerateStreamText other); @@ -103,9 +100,6 @@ public interface IsFinishedStage { public interface _FinalStage { GenerateStreamText build(); - /** - *

      Refers to the nth generation. Only present when num_generations is greater than zero, and only when text responses are being streamed.

      - */ _FinalStage index(Optional index); _FinalStage index(Integer index); @@ -133,7 +127,6 @@ public Builder from(GenerateStreamText other) { } /** - *

      A segment of text of the generation.

      *

      A segment of text of the generation.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -161,9 +154,6 @@ public _FinalStage index(Integer index) { return this; } - /** - *

      Refers to the nth generation. Only present when num_generations is greater than zero, and only when text responses are being streamed.

      - */ @java.lang.Override @JsonSetter(value = "index", nulls = Nulls.SKIP) public _FinalStage index(Optional index) { diff --git a/src/main/java/com/cohere/api/types/GenerateStreamedResponse.java b/src/main/java/com/cohere/api/types/GenerateStreamedResponse.java index 95799fb..96a238e 100644 --- a/src/main/java/com/cohere/api/types/GenerateStreamedResponse.java +++ b/src/main/java/com/cohere/api/types/GenerateStreamedResponse.java @@ -113,7 +113,6 @@ private interface Value { } @JsonTypeName("text-generation") - @JsonIgnoreProperties("event_type") private static final class TextGenerationValue implements Value { @JsonUnwrapped private GenerateStreamText value; @@ -152,7 +151,6 @@ public String toString() { } @JsonTypeName("stream-end") - @JsonIgnoreProperties("event_type") private static final class StreamEndValue implements Value { @JsonUnwrapped private GenerateStreamEnd value; @@ -191,7 +189,6 @@ public String toString() { } @JsonTypeName("stream-error") - @JsonIgnoreProperties("event_type") private static final class StreamErrorValue implements Value { @JsonUnwrapped private GenerateStreamError value; @@ -229,7 +226,6 @@ public String toString() { } } - @JsonIgnoreProperties("event_type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/Generation.java b/src/main/java/com/cohere/api/types/Generation.java index 543aa4e..bda515e 100644 --- a/src/main/java/com/cohere/api/types/Generation.java +++ b/src/main/java/com/cohere/api/types/Generation.java @@ -113,16 +113,10 @@ public interface IdStage { public interface _FinalStage { Generation build(); - /** - *

      Prompt used for generations.

      - */ _FinalStage prompt(Optional prompt); _FinalStage prompt(String prompt); - /** - *

      List of generated results

      - */ _FinalStage generations(List generations); _FinalStage addGenerations(SingleGeneration generations); @@ -198,9 +192,6 @@ public _FinalStage addGenerations(SingleGeneration generations) { return this; } - /** - *

      List of generated results

      - */ @java.lang.Override @JsonSetter(value = "generations", nulls = Nulls.SKIP) public _FinalStage generations(List generations) { @@ -219,9 +210,6 @@ public _FinalStage prompt(String prompt) { return this; } - /** - *

      Prompt used for generations.

      - */ @java.lang.Override @JsonSetter(value = "prompt", nulls = Nulls.SKIP) public _FinalStage prompt(Optional prompt) { diff --git a/src/main/java/com/cohere/api/types/GetModelResponse.java b/src/main/java/com/cohere/api/types/GetModelResponse.java index bd067c6..ea5cce5 100644 --- a/src/main/java/com/cohere/api/types/GetModelResponse.java +++ b/src/main/java/com/cohere/api/types/GetModelResponse.java @@ -220,9 +220,6 @@ public Builder from(GetModelResponse other) { return this; } - /** - *

      Specify this name in the model parameter of API requests to use your chosen model.

      - */ @JsonSetter(value = "name", nulls = Nulls.SKIP) public Builder name(Optional name) { this.name = name; @@ -234,9 +231,6 @@ public Builder name(String name) { return this; } - /** - *

      Whether the model is deprecated or not.

      - */ @JsonSetter(value = "is_deprecated", nulls = Nulls.SKIP) public Builder isDeprecated(Optional isDeprecated) { this.isDeprecated = isDeprecated; @@ -248,9 +242,6 @@ public Builder isDeprecated(Boolean isDeprecated) { return this; } - /** - *

      The API endpoints that the model is compatible with.

      - */ @JsonSetter(value = "endpoints", nulls = Nulls.SKIP) public Builder endpoints(Optional> endpoints) { this.endpoints = endpoints; @@ -262,9 +253,6 @@ public Builder endpoints(List endpoints) { return this; } - /** - *

      Whether the model has been fine-tuned or not.

      - */ @JsonSetter(value = "finetuned", nulls = Nulls.SKIP) public Builder finetuned(Optional finetuned) { this.finetuned = finetuned; @@ -276,9 +264,6 @@ public Builder finetuned(Boolean finetuned) { return this; } - /** - *

      The maximum number of tokens that the model can process in a single request. Note that not all of these tokens are always available due to special tokens and preambles that Cohere has added by default.

      - */ @JsonSetter(value = "context_length", nulls = Nulls.SKIP) public Builder contextLength(Optional contextLength) { this.contextLength = contextLength; @@ -290,9 +275,6 @@ public Builder contextLength(Double contextLength) { return this; } - /** - *

      Public URL to the tokenizer's configuration file.

      - */ @JsonSetter(value = "tokenizer_url", nulls = Nulls.SKIP) public Builder tokenizerUrl(Optional tokenizerUrl) { this.tokenizerUrl = tokenizerUrl; @@ -304,9 +286,6 @@ public Builder tokenizerUrl(String tokenizerUrl) { return this; } - /** - *

      Whether the model supports image inputs or not.

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

      The API endpoints that the model is default to.

      - */ @JsonSetter(value = "default_endpoints", nulls = Nulls.SKIP) public Builder defaultEndpoints(Optional> defaultEndpoints) { this.defaultEndpoints = defaultEndpoints; @@ -332,9 +308,6 @@ public Builder defaultEndpoints(List defaultEndpoints) { return this; } - /** - *

      The features that the model supports.

      - */ @JsonSetter(value = "features", nulls = Nulls.SKIP) public Builder features(Optional> features) { this.features = features; diff --git a/src/main/java/com/cohere/api/types/Image.java b/src/main/java/com/cohere/api/types/Image.java index c39d7bb..713b48c 100644 --- a/src/main/java/com/cohere/api/types/Image.java +++ b/src/main/java/com/cohere/api/types/Image.java @@ -102,32 +102,20 @@ public static WidthStage builder() { } public interface WidthStage { - /** - *

      Width of the image in pixels

      - */ HeightStage width(long width); Builder from(Image other); } public interface HeightStage { - /** - *

      Height of the image in pixels

      - */ FormatStage height(long height); } public interface FormatStage { - /** - *

      Format of the image

      - */ BitDepthStage format(@NotNull String format); } public interface BitDepthStage { - /** - *

      Bit depth of the image

      - */ _FinalStage bitDepth(long bitDepth); } @@ -160,7 +148,6 @@ public Builder from(Image other) { } /** - *

      Width of the image in pixels

      *

      Width of the image in pixels

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -172,7 +159,6 @@ public HeightStage width(long width) { } /** - *

      Height of the image in pixels

      *

      Height of the image in pixels

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -184,7 +170,6 @@ public FormatStage height(long height) { } /** - *

      Format of the image

      *

      Format of the image

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -196,7 +181,6 @@ public BitDepthStage format(@NotNull String format) { } /** - *

      Bit depth of the image

      *

      Bit depth of the image

      * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/ImageUrl.java b/src/main/java/com/cohere/api/types/ImageUrl.java index 0526537..8cd94cf 100644 --- a/src/main/java/com/cohere/api/types/ImageUrl.java +++ b/src/main/java/com/cohere/api/types/ImageUrl.java @@ -79,9 +79,6 @@ public static UrlStage builder() { } public interface UrlStage { - /** - *

      URL of an image. Can be either a base64 data URI or a web URL.

      - */ _FinalStage url(@NotNull String url); Builder from(ImageUrl other); @@ -90,9 +87,6 @@ public interface UrlStage { public interface _FinalStage { ImageUrl build(); - /** - *

      Controls the level of detail in image processing. "auto" is the default and lets the system choose, "low" is faster but less detailed, and "high" preserves maximum detail. You can save tokens and speed up responses by using detail: "low".

      - */ _FinalStage detail(Optional detail); _FinalStage detail(ImageUrlDetail detail); @@ -117,7 +111,6 @@ public Builder from(ImageUrl other) { } /** - *

      URL of an image. Can be either a base64 data URI or a web URL.

      *

      URL of an image. Can be either a base64 data URI or a web URL.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -138,9 +131,6 @@ public _FinalStage detail(ImageUrlDetail detail) { return this; } - /** - *

      Controls the level of detail in image processing. "auto" is the default and lets the system choose, "low" is faster but less detailed, and "high" preserves maximum detail. You can save tokens and speed up responses by using detail: "low".

      - */ @java.lang.Override @JsonSetter(value = "detail", nulls = Nulls.SKIP) public _FinalStage detail(Optional detail) { diff --git a/src/main/java/com/cohere/api/types/JsonResponseFormat.java b/src/main/java/com/cohere/api/types/JsonResponseFormat.java index 4eb8712..fb1d06b 100644 --- a/src/main/java/com/cohere/api/types/JsonResponseFormat.java +++ b/src/main/java/com/cohere/api/types/JsonResponseFormat.java @@ -91,20 +91,6 @@ public Builder from(JsonResponseFormat other) { return this; } - /** - *

      A JSON schema object that the output will adhere to. There are some restrictions we have on the schema, refer to our guide for more information. - * Example (required name and age object):

      - *
      {
      -         *   "type": "object",
      -         *   "properties": {
      -         *     "name": {"type": "string"},
      -         *     "age": {"type": "integer"}
      -         *   },
      -         *   "required": ["name", "age"]
      -         * }
      -         * 
      - *

      Note: This field must not be specified when the type is set to "text".

      - */ @JsonSetter(value = "schema", nulls = Nulls.SKIP) public Builder schema(Optional> schema) { this.schema = schema; diff --git a/src/main/java/com/cohere/api/types/JsonResponseFormatV2.java b/src/main/java/com/cohere/api/types/JsonResponseFormatV2.java index 11d702c..0a49804 100644 --- a/src/main/java/com/cohere/api/types/JsonResponseFormatV2.java +++ b/src/main/java/com/cohere/api/types/JsonResponseFormatV2.java @@ -91,20 +91,6 @@ public Builder from(JsonResponseFormatV2 other) { return this; } - /** - *

      A JSON schema object that the output will adhere to. There are some restrictions we have on the schema, refer to our guide for more information. - * Example (required name and age object):

      - *
      {
      -         *   "type": "object",
      -         *   "properties": {
      -         *     "name": {"type": "string"},
      -         *     "age": {"type": "integer"}
      -         *   },
      -         *   "required": ["name", "age"]
      -         * }
      -         * 
      - *

      Note: This field must not be specified when the type is set to "text".

      - */ @JsonSetter(value = "json_schema", nulls = Nulls.SKIP) public Builder jsonSchema(Optional> jsonSchema) { this.jsonSchema = jsonSchema; diff --git a/src/main/java/com/cohere/api/types/LabelMetric.java b/src/main/java/com/cohere/api/types/LabelMetric.java index 1806ac5..f916619 100644 --- a/src/main/java/com/cohere/api/types/LabelMetric.java +++ b/src/main/java/com/cohere/api/types/LabelMetric.java @@ -113,9 +113,6 @@ public Builder from(LabelMetric other) { return this; } - /** - *

      Total number of examples for this label

      - */ @JsonSetter(value = "total_examples", nulls = Nulls.SKIP) public Builder totalExamples(Optional totalExamples) { this.totalExamples = totalExamples; @@ -127,9 +124,6 @@ public Builder totalExamples(Long totalExamples) { return this; } - /** - *

      value of the label

      - */ @JsonSetter(value = "label", nulls = Nulls.SKIP) public Builder label(Optional label) { this.label = label; @@ -141,9 +135,6 @@ public Builder label(String label) { return this; } - /** - *

      samples for this label

      - */ @JsonSetter(value = "samples", nulls = Nulls.SKIP) public Builder samples(Optional> samples) { this.samples = samples; diff --git a/src/main/java/com/cohere/api/types/ListConnectorsResponse.java b/src/main/java/com/cohere/api/types/ListConnectorsResponse.java index 32bfe06..770edc7 100644 --- a/src/main/java/com/cohere/api/types/ListConnectorsResponse.java +++ b/src/main/java/com/cohere/api/types/ListConnectorsResponse.java @@ -111,9 +111,6 @@ public Builder addAllConnectors(List connectors) { return this; } - /** - *

      Total number of connectors.

      - */ @JsonSetter(value = "total_count", nulls = Nulls.SKIP) public Builder totalCount(Optional totalCount) { this.totalCount = totalCount; diff --git a/src/main/java/com/cohere/api/types/ListModelsResponse.java b/src/main/java/com/cohere/api/types/ListModelsResponse.java index d0b7c91..7f69d6e 100644 --- a/src/main/java/com/cohere/api/types/ListModelsResponse.java +++ b/src/main/java/com/cohere/api/types/ListModelsResponse.java @@ -111,9 +111,6 @@ public Builder addAllModels(List models) { return this; } - /** - *

      A token to retrieve the next page of results. Provide in the page_token parameter of the next request.

      - */ @JsonSetter(value = "next_page_token", nulls = Nulls.SKIP) public Builder nextPageToken(Optional nextPageToken) { this.nextPageToken = nextPageToken; diff --git a/src/main/java/com/cohere/api/types/LogprobItem.java b/src/main/java/com/cohere/api/types/LogprobItem.java index eff8c7b..83aaf20 100644 --- a/src/main/java/com/cohere/api/types/LogprobItem.java +++ b/src/main/java/com/cohere/api/types/LogprobItem.java @@ -114,9 +114,6 @@ public Builder from(LogprobItem other) { return this; } - /** - *

      The text chunk for which the log probabilities was calculated.

      - */ @JsonSetter(value = "text", nulls = Nulls.SKIP) public Builder text(Optional text) { this.text = text; @@ -128,9 +125,6 @@ public Builder text(String text) { return this; } - /** - *

      The token ids of each token used to construct the text chunk.

      - */ @JsonSetter(value = "token_ids", nulls = Nulls.SKIP) public Builder tokenIds(List tokenIds) { this.tokenIds.clear(); @@ -148,9 +142,6 @@ public Builder addAllTokenIds(List tokenIds) { return this; } - /** - *

      The log probability of each token used to construct the text chunk.

      - */ @JsonSetter(value = "logprobs", nulls = Nulls.SKIP) public Builder logprobs(Optional> logprobs) { this.logprobs = logprobs; diff --git a/src/main/java/com/cohere/api/types/Message.java b/src/main/java/com/cohere/api/types/Message.java index 844ad1b..c8749a6 100644 --- a/src/main/java/com/cohere/api/types/Message.java +++ b/src/main/java/com/cohere/api/types/Message.java @@ -127,7 +127,6 @@ private interface Value { } @JsonTypeName("CHATBOT") - @JsonIgnoreProperties("role") private static final class ChatbotValue implements Value { @JsonUnwrapped private ChatMessage value; @@ -166,7 +165,6 @@ public String toString() { } @JsonTypeName("SYSTEM") - @JsonIgnoreProperties("role") private static final class SystemValue implements Value { @JsonUnwrapped private ChatMessage value; @@ -205,7 +203,6 @@ public String toString() { } @JsonTypeName("USER") - @JsonIgnoreProperties("role") private static final class UserValue implements Value { @JsonUnwrapped private ChatMessage value; @@ -244,7 +241,6 @@ public String toString() { } @JsonTypeName("TOOL") - @JsonIgnoreProperties("role") private static final class ToolValue implements Value { @JsonUnwrapped private ChatToolMessage value; @@ -282,7 +278,6 @@ public String toString() { } } - @JsonIgnoreProperties("role") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/Metrics.java b/src/main/java/com/cohere/api/types/Metrics.java index 1cf28bc..aa236bc 100644 --- a/src/main/java/com/cohere/api/types/Metrics.java +++ b/src/main/java/com/cohere/api/types/Metrics.java @@ -22,10 +22,16 @@ public final class Metrics { private final Optional finetuneDatasetMetrics; + private final Optional embedData; + private final Map additionalProperties; - private Metrics(Optional finetuneDatasetMetrics, Map additionalProperties) { + private Metrics( + Optional finetuneDatasetMetrics, + Optional embedData, + Map additionalProperties) { this.finetuneDatasetMetrics = finetuneDatasetMetrics; + this.embedData = embedData; this.additionalProperties = additionalProperties; } @@ -34,6 +40,11 @@ public Optional getFinetuneDatasetMetrics() { return finetuneDatasetMetrics; } + @JsonProperty("embed_data") + public Optional getEmbedData() { + return embedData; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -46,12 +57,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(Metrics other) { - return finetuneDatasetMetrics.equals(other.finetuneDatasetMetrics); + return finetuneDatasetMetrics.equals(other.finetuneDatasetMetrics) && embedData.equals(other.embedData); } @java.lang.Override public int hashCode() { - return Objects.hash(this.finetuneDatasetMetrics); + return Objects.hash(this.finetuneDatasetMetrics, this.embedData); } @java.lang.Override @@ -67,6 +78,8 @@ public static Builder builder() { public static final class Builder { private Optional finetuneDatasetMetrics = Optional.empty(); + private Optional embedData = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -74,6 +87,7 @@ private Builder() {} public Builder from(Metrics other) { finetuneDatasetMetrics(other.getFinetuneDatasetMetrics()); + embedData(other.getEmbedData()); return this; } @@ -88,8 +102,19 @@ public Builder finetuneDatasetMetrics(FinetuneDatasetMetrics finetuneDatasetMetr return this; } + @JsonSetter(value = "embed_data", nulls = Nulls.SKIP) + public Builder embedData(Optional embedData) { + this.embedData = embedData; + return this; + } + + public Builder embedData(MetricsEmbedData embedData) { + this.embedData = Optional.ofNullable(embedData); + return this; + } + public Metrics build() { - return new Metrics(finetuneDatasetMetrics, additionalProperties); + return new Metrics(finetuneDatasetMetrics, embedData, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/types/MetricsEmbedData.java b/src/main/java/com/cohere/api/types/MetricsEmbedData.java new file mode 100644 index 0000000..11c8aea --- /dev/null +++ b/src/main/java/com/cohere/api/types/MetricsEmbedData.java @@ -0,0 +1,100 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = MetricsEmbedData.Builder.class) +public final class MetricsEmbedData { + private final Optional> fields; + + private final Map additionalProperties; + + private MetricsEmbedData( + Optional> fields, Map additionalProperties) { + this.fields = fields; + this.additionalProperties = additionalProperties; + } + + /** + * @return the fields in the dataset + */ + @JsonProperty("fields") + public Optional> getFields() { + return fields; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof MetricsEmbedData && equalTo((MetricsEmbedData) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(MetricsEmbedData other) { + return fields.equals(other.fields); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.fields); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> fields = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(MetricsEmbedData other) { + fields(other.getFields()); + return this; + } + + @JsonSetter(value = "fields", nulls = Nulls.SKIP) + public Builder fields(Optional> fields) { + this.fields = fields; + return this; + } + + public Builder fields(List fields) { + this.fields = Optional.ofNullable(fields); + return this; + } + + public MetricsEmbedData build() { + return new MetricsEmbedData(fields, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/types/MetricsEmbedDataFieldsItem.java b/src/main/java/com/cohere/api/types/MetricsEmbedDataFieldsItem.java new file mode 100644 index 0000000..a79578b --- /dev/null +++ b/src/main/java/com/cohere/api/types/MetricsEmbedDataFieldsItem.java @@ -0,0 +1,124 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = MetricsEmbedDataFieldsItem.Builder.class) +public final class MetricsEmbedDataFieldsItem { + private final Optional name; + + private final Optional count; + + private final Map additionalProperties; + + private MetricsEmbedDataFieldsItem( + Optional name, Optional count, Map additionalProperties) { + this.name = name; + this.count = count; + this.additionalProperties = additionalProperties; + } + + /** + * @return the name of the field + */ + @JsonProperty("name") + public Optional getName() { + return name; + } + + /** + * @return the number of times the field appears in the dataset + */ + @JsonProperty("count") + public Optional getCount() { + return count; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof MetricsEmbedDataFieldsItem && equalTo((MetricsEmbedDataFieldsItem) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(MetricsEmbedDataFieldsItem other) { + return name.equals(other.name) && count.equals(other.count); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.name, this.count); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional name = Optional.empty(); + + private Optional count = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(MetricsEmbedDataFieldsItem other) { + name(other.getName()); + count(other.getCount()); + return this; + } + + @JsonSetter(value = "name", nulls = Nulls.SKIP) + public Builder name(Optional name) { + this.name = name; + return this; + } + + public Builder name(String name) { + this.name = Optional.ofNullable(name); + return this; + } + + @JsonSetter(value = "count", nulls = Nulls.SKIP) + public Builder count(Optional count) { + this.count = count; + return this; + } + + public Builder count(Double count) { + this.count = Optional.ofNullable(count); + return this; + } + + public MetricsEmbedDataFieldsItem build() { + return new MetricsEmbedDataFieldsItem(name, count, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/types/NonStreamedChatResponse.java b/src/main/java/com/cohere/api/types/NonStreamedChatResponse.java index 521e4c3..05338bc 100644 --- a/src/main/java/com/cohere/api/types/NonStreamedChatResponse.java +++ b/src/main/java/com/cohere/api/types/NonStreamedChatResponse.java @@ -44,6 +44,8 @@ public final class NonStreamedChatResponse { private final Optional> chatHistory; + private final Optional prompt; + private final Optional meta; private final Map additionalProperties; @@ -60,6 +62,7 @@ private NonStreamedChatResponse( Optional finishReason, Optional> toolCalls, Optional> chatHistory, + Optional prompt, Optional meta, Map additionalProperties) { this.text = text; @@ -73,6 +76,7 @@ private NonStreamedChatResponse( this.finishReason = finishReason; this.toolCalls = toolCalls; this.chatHistory = chatHistory; + this.prompt = prompt; this.meta = meta; this.additionalProperties = additionalProperties; } @@ -159,6 +163,14 @@ public Optional> getChatHistory() { return chatHistory; } + /** + * @return The prompt that was used. Only present when return_prompt in the request is set to true. + */ + @JsonProperty("prompt") + public Optional getPrompt() { + return prompt; + } + @JsonProperty("meta") public Optional getMeta() { return meta; @@ -187,6 +199,7 @@ private boolean equalTo(NonStreamedChatResponse other) { && finishReason.equals(other.finishReason) && toolCalls.equals(other.toolCalls) && chatHistory.equals(other.chatHistory) + && prompt.equals(other.prompt) && meta.equals(other.meta); } @@ -204,6 +217,7 @@ public int hashCode() { this.finishReason, this.toolCalls, this.chatHistory, + this.prompt, this.meta); } @@ -217,9 +231,6 @@ public static TextStage builder() { } public interface TextStage { - /** - *

      Contents of the reply generated by the model.

      - */ _FinalStage text(@NotNull String text); Builder from(NonStreamedChatResponse other); @@ -228,51 +239,30 @@ public interface TextStage { public interface _FinalStage { NonStreamedChatResponse build(); - /** - *

      Unique identifier for the generated reply. Useful for submitting feedback.

      - */ _FinalStage generationId(Optional generationId); _FinalStage generationId(String generationId); - /** - *

      Unique identifier for the response.

      - */ _FinalStage responseId(Optional responseId); _FinalStage responseId(String responseId); - /** - *

      Inline citations for the generated reply.

      - */ _FinalStage citations(Optional> citations); _FinalStage citations(List citations); - /** - *

      Documents seen by the model when generating the reply.

      - */ _FinalStage documents(Optional>> documents); _FinalStage documents(List> documents); - /** - *

      Denotes that a search for documents is required during the RAG flow.

      - */ _FinalStage isSearchRequired(Optional isSearchRequired); _FinalStage isSearchRequired(Boolean isSearchRequired); - /** - *

      Generated search queries, meant to be used as part of the RAG flow.

      - */ _FinalStage searchQueries(Optional> searchQueries); _FinalStage searchQueries(List searchQueries); - /** - *

      Documents retrieved from each of the conducted searches.

      - */ _FinalStage searchResults(Optional> searchResults); _FinalStage searchResults(List searchResults); @@ -285,13 +275,14 @@ public interface _FinalStage { _FinalStage toolCalls(List toolCalls); - /** - *

      A list of previous messages between the user and the model, meant to give the model conversational context for responding to the user's message.

      - */ _FinalStage chatHistory(Optional> chatHistory); _FinalStage chatHistory(List chatHistory); + _FinalStage prompt(Optional prompt); + + _FinalStage prompt(String prompt); + _FinalStage meta(Optional meta); _FinalStage meta(ApiMeta meta); @@ -303,6 +294,8 @@ public static final class Builder implements TextStage, _FinalStage { private Optional meta = Optional.empty(); + private Optional prompt = Optional.empty(); + private Optional> chatHistory = Optional.empty(); private Optional> toolCalls = Optional.empty(); @@ -341,12 +334,12 @@ public Builder from(NonStreamedChatResponse other) { finishReason(other.getFinishReason()); toolCalls(other.getToolCalls()); chatHistory(other.getChatHistory()); + prompt(other.getPrompt()); meta(other.getMeta()); return this; } /** - *

      Contents of the reply generated by the model.

      *

      Contents of the reply generated by the model.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -371,18 +364,32 @@ public _FinalStage meta(Optional meta) { } /** - *

      A list of previous messages between the user and the model, meant to give the model conversational context for responding to the user's message.

      + *

      The prompt that was used. Only present when return_prompt in the request is set to true.

      * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage chatHistory(List chatHistory) { - this.chatHistory = Optional.ofNullable(chatHistory); + public _FinalStage prompt(String prompt) { + this.prompt = Optional.ofNullable(prompt); + return this; + } + + @java.lang.Override + @JsonSetter(value = "prompt", nulls = Nulls.SKIP) + public _FinalStage prompt(Optional prompt) { + this.prompt = prompt; return this; } /** *

      A list of previous messages between the user and the model, meant to give the model conversational context for responding to the user's message.

      + * @return Reference to {@code this} so that method calls can be chained together. */ + @java.lang.Override + public _FinalStage chatHistory(List chatHistory) { + this.chatHistory = Optional.ofNullable(chatHistory); + return this; + } + @java.lang.Override @JsonSetter(value = "chat_history", nulls = Nulls.SKIP) public _FinalStage chatHistory(Optional> chatHistory) { @@ -426,9 +433,6 @@ public _FinalStage searchResults(List searchResults) { return this; } - /** - *

      Documents retrieved from each of the conducted searches.

      - */ @java.lang.Override @JsonSetter(value = "search_results", nulls = Nulls.SKIP) public _FinalStage searchResults(Optional> searchResults) { @@ -446,9 +450,6 @@ public _FinalStage searchQueries(List searchQueries) { return this; } - /** - *

      Generated search queries, meant to be used as part of the RAG flow.

      - */ @java.lang.Override @JsonSetter(value = "search_queries", nulls = Nulls.SKIP) public _FinalStage searchQueries(Optional> searchQueries) { @@ -466,9 +467,6 @@ public _FinalStage isSearchRequired(Boolean isSearchRequired) { return this; } - /** - *

      Denotes that a search for documents is required during the RAG flow.

      - */ @java.lang.Override @JsonSetter(value = "is_search_required", nulls = Nulls.SKIP) public _FinalStage isSearchRequired(Optional isSearchRequired) { @@ -486,9 +484,6 @@ public _FinalStage documents(List> documents) { return this; } - /** - *

      Documents seen by the model when generating the reply.

      - */ @java.lang.Override @JsonSetter(value = "documents", nulls = Nulls.SKIP) public _FinalStage documents(Optional>> documents) { @@ -506,9 +501,6 @@ public _FinalStage citations(List citations) { return this; } - /** - *

      Inline citations for the generated reply.

      - */ @java.lang.Override @JsonSetter(value = "citations", nulls = Nulls.SKIP) public _FinalStage citations(Optional> citations) { @@ -526,9 +518,6 @@ public _FinalStage responseId(String responseId) { return this; } - /** - *

      Unique identifier for the response.

      - */ @java.lang.Override @JsonSetter(value = "response_id", nulls = Nulls.SKIP) public _FinalStage responseId(Optional responseId) { @@ -546,9 +535,6 @@ public _FinalStage generationId(String generationId) { return this; } - /** - *

      Unique identifier for the generated reply. Useful for submitting feedback.

      - */ @java.lang.Override @JsonSetter(value = "generation_id", nulls = Nulls.SKIP) public _FinalStage generationId(Optional generationId) { @@ -570,6 +556,7 @@ public NonStreamedChatResponse build() { finishReason, toolCalls, chatHistory, + prompt, meta, additionalProperties); } diff --git a/src/main/java/com/cohere/api/types/OAuthAuthorizeResponse.java b/src/main/java/com/cohere/api/types/OAuthAuthorizeResponse.java index be5cd8b..9526b5d 100644 --- a/src/main/java/com/cohere/api/types/OAuthAuthorizeResponse.java +++ b/src/main/java/com/cohere/api/types/OAuthAuthorizeResponse.java @@ -80,9 +80,6 @@ public Builder from(OAuthAuthorizeResponse other) { return this; } - /** - *

      The OAuth 2.0 redirect url. Redirect the user to this url to authorize the connector.

      - */ @JsonSetter(value = "redirect_url", nulls = Nulls.SKIP) public Builder redirectUrl(Optional redirectUrl) { this.redirectUrl = redirectUrl; diff --git a/src/main/java/com/cohere/api/types/RerankRequestDocumentsItem.java b/src/main/java/com/cohere/api/types/RerankRequestDocumentsItem.java index 0daa723..852c78c 100644 --- a/src/main/java/com/cohere/api/types/RerankRequestDocumentsItem.java +++ b/src/main/java/com/cohere/api/types/RerankRequestDocumentsItem.java @@ -31,7 +31,6 @@ public Object get() { return this.value; } - @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if (this.type == 0) { return visitor.visit((String) this.value); @@ -81,7 +80,7 @@ static final class Deserializer extends StdDeserializerAn ordered list of ranked documents

      - */ @JsonSetter(value = "results", nulls = Nulls.SKIP) public Builder results(List results) { this.results.clear(); diff --git a/src/main/java/com/cohere/api/types/RerankResponseResultsItem.java b/src/main/java/com/cohere/api/types/RerankResponseResultsItem.java index 128fcff..87ff779 100644 --- a/src/main/java/com/cohere/api/types/RerankResponseResultsItem.java +++ b/src/main/java/com/cohere/api/types/RerankResponseResultsItem.java @@ -93,27 +93,18 @@ public static IndexStage builder() { } public interface IndexStage { - /** - *

      Corresponds to the index in the original list of documents to which the ranked document belongs. (i.e. if the first value in the results object has an index value of 3, it means in the list of documents passed in, the document at index=3 had the highest relevance)

      - */ RelevanceScoreStage index(int index); Builder from(RerankResponseResultsItem other); } public interface RelevanceScoreStage { - /** - *

      Relevance scores are normalized to be in the range [0, 1]. Scores close to 1 indicate a high relevance to the query, and scores closer to 0 indicate low relevance. It is not accurate to assume a score of 0.9 means the document is 2x more relevant than a document with a score of 0.45

      - */ _FinalStage relevanceScore(float relevanceScore); } public interface _FinalStage { RerankResponseResultsItem build(); - /** - *

      If return_documents is set as false this will return none, if true it will return the documents passed in

      - */ _FinalStage document(Optional document); _FinalStage document(RerankResponseResultsItemDocument document); @@ -141,7 +132,6 @@ public Builder from(RerankResponseResultsItem other) { } /** - *

      Corresponds to the index in the original list of documents to which the ranked document belongs. (i.e. if the first value in the results object has an index value of 3, it means in the list of documents passed in, the document at index=3 had the highest relevance)

      *

      Corresponds to the index in the original list of documents to which the ranked document belongs. (i.e. if the first value in the results object has an index value of 3, it means in the list of documents passed in, the document at index=3 had the highest relevance)

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -153,7 +143,6 @@ public RelevanceScoreStage index(int index) { } /** - *

      Relevance scores are normalized to be in the range [0, 1]. Scores close to 1 indicate a high relevance to the query, and scores closer to 0 indicate low relevance. It is not accurate to assume a score of 0.9 means the document is 2x more relevant than a document with a score of 0.45

      *

      Relevance scores are normalized to be in the range [0, 1]. Scores close to 1 indicate a high relevance to the query, and scores closer to 0 indicate low relevance. It is not accurate to assume a score of 0.9 means the document is 2x more relevant than a document with a score of 0.45

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -174,9 +163,6 @@ public _FinalStage document(RerankResponseResultsItemDocument document) { return this; } - /** - *

      If return_documents is set as false this will return none, if true it will return the documents passed in

      - */ @java.lang.Override @JsonSetter(value = "document", nulls = Nulls.SKIP) public _FinalStage document(Optional document) { diff --git a/src/main/java/com/cohere/api/types/RerankResponseResultsItemDocument.java b/src/main/java/com/cohere/api/types/RerankResponseResultsItemDocument.java index 6e2387c..a815a66 100644 --- a/src/main/java/com/cohere/api/types/RerankResponseResultsItemDocument.java +++ b/src/main/java/com/cohere/api/types/RerankResponseResultsItemDocument.java @@ -66,9 +66,6 @@ public static TextStage builder() { } public interface TextStage { - /** - *

      The text of the document to rerank

      - */ _FinalStage text(@NotNull String text); Builder from(RerankResponseResultsItemDocument other); @@ -94,7 +91,6 @@ public Builder from(RerankResponseResultsItemDocument other) { } /** - *

      The text of the document to rerank

      *

      The text of the document to rerank

      * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/RerankerDataMetrics.java b/src/main/java/com/cohere/api/types/RerankerDataMetrics.java index 833f743..6e086c5 100644 --- a/src/main/java/com/cohere/api/types/RerankerDataMetrics.java +++ b/src/main/java/com/cohere/api/types/RerankerDataMetrics.java @@ -168,9 +168,6 @@ public Builder from(RerankerDataMetrics other) { return this; } - /** - *

      The number of training queries.

      - */ @JsonSetter(value = "num_train_queries", nulls = Nulls.SKIP) public Builder numTrainQueries(Optional numTrainQueries) { this.numTrainQueries = numTrainQueries; @@ -182,9 +179,6 @@ public Builder numTrainQueries(Long numTrainQueries) { return this; } - /** - *

      The sum of all relevant passages of valid training examples.

      - */ @JsonSetter(value = "num_train_relevant_passages", nulls = Nulls.SKIP) public Builder numTrainRelevantPassages(Optional numTrainRelevantPassages) { this.numTrainRelevantPassages = numTrainRelevantPassages; @@ -196,9 +190,6 @@ public Builder numTrainRelevantPassages(Long numTrainRelevantPassages) { return this; } - /** - *

      The sum of all hard negatives of valid training examples.

      - */ @JsonSetter(value = "num_train_hard_negatives", nulls = Nulls.SKIP) public Builder numTrainHardNegatives(Optional numTrainHardNegatives) { this.numTrainHardNegatives = numTrainHardNegatives; @@ -210,9 +201,6 @@ public Builder numTrainHardNegatives(Long numTrainHardNegatives) { return this; } - /** - *

      The number of evaluation queries.

      - */ @JsonSetter(value = "num_eval_queries", nulls = Nulls.SKIP) public Builder numEvalQueries(Optional numEvalQueries) { this.numEvalQueries = numEvalQueries; @@ -224,9 +212,6 @@ public Builder numEvalQueries(Long numEvalQueries) { return this; } - /** - *

      The sum of all relevant passages of valid eval examples.

      - */ @JsonSetter(value = "num_eval_relevant_passages", nulls = Nulls.SKIP) public Builder numEvalRelevantPassages(Optional numEvalRelevantPassages) { this.numEvalRelevantPassages = numEvalRelevantPassages; @@ -238,9 +223,6 @@ public Builder numEvalRelevantPassages(Long numEvalRelevantPassages) { return this; } - /** - *

      The sum of all hard negatives of valid eval examples.

      - */ @JsonSetter(value = "num_eval_hard_negatives", nulls = Nulls.SKIP) public Builder numEvalHardNegatives(Optional numEvalHardNegatives) { this.numEvalHardNegatives = numEvalHardNegatives; diff --git a/src/main/java/com/cohere/api/types/ResponseFormat.java b/src/main/java/com/cohere/api/types/ResponseFormat.java index 74cbf35..2cbac7a 100644 --- a/src/main/java/com/cohere/api/types/ResponseFormat.java +++ b/src/main/java/com/cohere/api/types/ResponseFormat.java @@ -88,7 +88,6 @@ private interface Value { } @JsonTypeName("text") - @JsonIgnoreProperties("type") private static final class TextValue implements Value { @JsonUnwrapped private ChatTextResponseFormat value; @@ -127,7 +126,6 @@ public String toString() { } @JsonTypeName("json_object") - @JsonIgnoreProperties("type") private static final class JsonObjectValue implements Value { @JsonUnwrapped private JsonResponseFormat value; @@ -165,7 +163,6 @@ public String toString() { } } - @JsonIgnoreProperties("type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/ResponseFormatV2.java b/src/main/java/com/cohere/api/types/ResponseFormatV2.java index 7d938b4..8f2df66 100644 --- a/src/main/java/com/cohere/api/types/ResponseFormatV2.java +++ b/src/main/java/com/cohere/api/types/ResponseFormatV2.java @@ -88,7 +88,6 @@ private interface Value { } @JsonTypeName("text") - @JsonIgnoreProperties("type") private static final class TextValue implements Value { @JsonUnwrapped private ChatTextResponseFormatV2 value; @@ -127,7 +126,6 @@ public String toString() { } @JsonTypeName("json_object") - @JsonIgnoreProperties("type") private static final class JsonObjectValue implements Value { @JsonUnwrapped private JsonResponseFormatV2 value; @@ -165,7 +163,6 @@ public String toString() { } } - @JsonIgnoreProperties("type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/SingleGeneration.java b/src/main/java/com/cohere/api/types/SingleGeneration.java index 48614a0..2428e7b 100644 --- a/src/main/java/com/cohere/api/types/SingleGeneration.java +++ b/src/main/java/com/cohere/api/types/SingleGeneration.java @@ -126,9 +126,6 @@ public interface TextStage { public interface _FinalStage { SingleGeneration build(); - /** - *

      Refers to the nth generation. Only present when num_generations is greater than zero.

      - */ _FinalStage index(Optional index); _FinalStage index(Integer index); @@ -137,9 +134,6 @@ public interface _FinalStage { _FinalStage likelihood(Double likelihood); - /** - *

      Only returned if return_likelihoods is set to GENERATION or ALL. The likelihood refers to the average log-likelihood of the entire specified string, which is useful for evaluating the performance of your model, especially if you've created a custom model. Individual token likelihoods provide the log-likelihood of each token. The first token will not have a likelihood.

      - */ _FinalStage tokenLikelihoods(Optional> tokenLikelihoods); _FinalStage tokenLikelihoods(List tokenLikelihoods); @@ -196,9 +190,6 @@ public _FinalStage tokenLikelihoods(List t return this; } - /** - *

      Only returned if return_likelihoods is set to GENERATION or ALL. The likelihood refers to the average log-likelihood of the entire specified string, which is useful for evaluating the performance of your model, especially if you've created a custom model. Individual token likelihoods provide the log-likelihood of each token. The first token will not have a likelihood.

      - */ @java.lang.Override @JsonSetter(value = "token_likelihoods", nulls = Nulls.SKIP) public _FinalStage tokenLikelihoods(Optional> tokenLikelihoods) { @@ -229,9 +220,6 @@ public _FinalStage index(Integer index) { return this; } - /** - *

      Refers to the nth generation. Only present when num_generations is greater than zero.

      - */ @java.lang.Override @JsonSetter(value = "index", nulls = Nulls.SKIP) public _FinalStage index(Optional index) { diff --git a/src/main/java/com/cohere/api/types/SingleGenerationInStream.java b/src/main/java/com/cohere/api/types/SingleGenerationInStream.java index b4ff6a2..c7784c5 100644 --- a/src/main/java/com/cohere/api/types/SingleGenerationInStream.java +++ b/src/main/java/com/cohere/api/types/SingleGenerationInStream.java @@ -109,9 +109,6 @@ public interface IdStage { } public interface TextStage { - /** - *

      Full text of the generation.

      - */ FinishReasonStage text(@NotNull String text); } @@ -122,9 +119,6 @@ public interface FinishReasonStage { public interface _FinalStage { SingleGenerationInStream build(); - /** - *

      Refers to the nth generation. Only present when num_generations is greater than zero.

      - */ _FinalStage index(Optional index); _FinalStage index(Integer index); @@ -162,7 +156,6 @@ public TextStage id(@NotNull String id) { } /** - *

      Full text of the generation.

      *

      Full text of the generation.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -190,9 +183,6 @@ public _FinalStage index(Integer index) { return this; } - /** - *

      Refers to the nth generation. Only present when num_generations is greater than zero.

      - */ @java.lang.Override @JsonSetter(value = "index", nulls = Nulls.SKIP) public _FinalStage index(Optional index) { diff --git a/src/main/java/com/cohere/api/types/Source.java b/src/main/java/com/cohere/api/types/Source.java index c8d1435..21250f0 100644 --- a/src/main/java/com/cohere/api/types/Source.java +++ b/src/main/java/com/cohere/api/types/Source.java @@ -88,7 +88,6 @@ private interface Value { } @JsonTypeName("tool") - @JsonIgnoreProperties("type") private static final class ToolValue implements Value { @JsonUnwrapped private ChatToolSource value; @@ -127,7 +126,6 @@ public String toString() { } @JsonTypeName("document") - @JsonIgnoreProperties("type") private static final class DocumentValue implements Value { @JsonUnwrapped private ChatDocumentSource value; @@ -165,7 +163,6 @@ public String toString() { } } - @JsonIgnoreProperties("type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/StreamedChatResponse.java b/src/main/java/com/cohere/api/types/StreamedChatResponse.java index 28ab0f0..3db861b 100644 --- a/src/main/java/com/cohere/api/types/StreamedChatResponse.java +++ b/src/main/java/com/cohere/api/types/StreamedChatResponse.java @@ -221,7 +221,6 @@ private interface Value { } @JsonTypeName("stream-start") - @JsonIgnoreProperties("event_type") private static final class StreamStartValue implements Value { @JsonUnwrapped private ChatStreamStartEvent value; @@ -260,7 +259,6 @@ public String toString() { } @JsonTypeName("search-queries-generation") - @JsonIgnoreProperties("event_type") private static final class SearchQueriesGenerationValue implements Value { @JsonUnwrapped private ChatSearchQueriesGenerationEvent value; @@ -299,7 +297,6 @@ public String toString() { } @JsonTypeName("search-results") - @JsonIgnoreProperties("event_type") private static final class SearchResultsValue implements Value { @JsonUnwrapped private ChatSearchResultsEvent value; @@ -338,7 +335,6 @@ public String toString() { } @JsonTypeName("text-generation") - @JsonIgnoreProperties("event_type") private static final class TextGenerationValue implements Value { @JsonUnwrapped private ChatTextGenerationEvent value; @@ -377,7 +373,6 @@ public String toString() { } @JsonTypeName("citation-generation") - @JsonIgnoreProperties("event_type") private static final class CitationGenerationValue implements Value { @JsonUnwrapped private ChatCitationGenerationEvent value; @@ -416,7 +411,6 @@ public String toString() { } @JsonTypeName("tool-calls-generation") - @JsonIgnoreProperties("event_type") private static final class ToolCallsGenerationValue implements Value { @JsonUnwrapped private ChatToolCallsGenerationEvent value; @@ -455,7 +449,6 @@ public String toString() { } @JsonTypeName("stream-end") - @JsonIgnoreProperties("event_type") private static final class StreamEndValue implements Value { @JsonUnwrapped private ChatStreamEndEvent value; @@ -494,7 +487,6 @@ public String toString() { } @JsonTypeName("tool-calls-chunk") - @JsonIgnoreProperties("event_type") private static final class ToolCallsChunkValue implements Value { @JsonUnwrapped private ChatToolCallsChunkEvent value; @@ -533,7 +525,6 @@ public String toString() { } @JsonTypeName("debug") - @JsonIgnoreProperties("event_type") private static final class DebugValue implements Value { @JsonUnwrapped private ChatDebugEvent value; @@ -571,7 +562,6 @@ public String toString() { } } - @JsonIgnoreProperties("event_type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamResponse.java b/src/main/java/com/cohere/api/types/StreamedChatResponseV2.java similarity index 84% rename from src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamResponse.java rename to src/main/java/com/cohere/api/types/StreamedChatResponseV2.java index f746500..0e29016 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamResponse.java +++ b/src/main/java/com/cohere/api/types/StreamedChatResponseV2.java @@ -1,20 +1,8 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.cohere.api.resources.v2.types; - -import com.cohere.api.types.ChatContentDeltaEvent; -import com.cohere.api.types.ChatContentEndEvent; -import com.cohere.api.types.ChatContentStartEvent; -import com.cohere.api.types.ChatDebugEvent; -import com.cohere.api.types.ChatMessageEndEvent; -import com.cohere.api.types.ChatMessageStartEvent; -import com.cohere.api.types.ChatToolCallDeltaEvent; -import com.cohere.api.types.ChatToolCallEndEvent; -import com.cohere.api.types.ChatToolCallStartEvent; -import com.cohere.api.types.ChatToolPlanDeltaEvent; -import com.cohere.api.types.CitationEndEvent; -import com.cohere.api.types.CitationStartEvent; +package com.cohere.api.types; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -26,11 +14,11 @@ import java.util.Objects; import java.util.Optional; -public final class V2ChatStreamResponse { +public final class StreamedChatResponseV2 { private final Value value; @JsonCreator(mode = JsonCreator.Mode.DELEGATING) - private V2ChatStreamResponse(Value value) { + private StreamedChatResponseV2(Value value) { this.value = value; } @@ -38,52 +26,52 @@ public T visit(Visitor visitor) { return value.visit(visitor); } - public static V2ChatStreamResponse messageStart(ChatMessageStartEvent value) { - return new V2ChatStreamResponse(new MessageStartValue(value)); + public static StreamedChatResponseV2 messageStart(ChatMessageStartEvent value) { + return new StreamedChatResponseV2(new MessageStartValue(value)); } - public static V2ChatStreamResponse contentStart(ChatContentStartEvent value) { - return new V2ChatStreamResponse(new ContentStartValue(value)); + public static StreamedChatResponseV2 contentStart(ChatContentStartEvent value) { + return new StreamedChatResponseV2(new ContentStartValue(value)); } - public static V2ChatStreamResponse contentDelta(ChatContentDeltaEvent value) { - return new V2ChatStreamResponse(new ContentDeltaValue(value)); + public static StreamedChatResponseV2 contentDelta(ChatContentDeltaEvent value) { + return new StreamedChatResponseV2(new ContentDeltaValue(value)); } - public static V2ChatStreamResponse contentEnd(ChatContentEndEvent value) { - return new V2ChatStreamResponse(new ContentEndValue(value)); + public static StreamedChatResponseV2 contentEnd(ChatContentEndEvent value) { + return new StreamedChatResponseV2(new ContentEndValue(value)); } - public static V2ChatStreamResponse toolPlanDelta(ChatToolPlanDeltaEvent value) { - return new V2ChatStreamResponse(new ToolPlanDeltaValue(value)); + public static StreamedChatResponseV2 toolPlanDelta(ChatToolPlanDeltaEvent value) { + return new StreamedChatResponseV2(new ToolPlanDeltaValue(value)); } - public static V2ChatStreamResponse toolCallStart(ChatToolCallStartEvent value) { - return new V2ChatStreamResponse(new ToolCallStartValue(value)); + public static StreamedChatResponseV2 toolCallStart(ChatToolCallStartEvent value) { + return new StreamedChatResponseV2(new ToolCallStartValue(value)); } - public static V2ChatStreamResponse toolCallDelta(ChatToolCallDeltaEvent value) { - return new V2ChatStreamResponse(new ToolCallDeltaValue(value)); + public static StreamedChatResponseV2 toolCallDelta(ChatToolCallDeltaEvent value) { + return new StreamedChatResponseV2(new ToolCallDeltaValue(value)); } - public static V2ChatStreamResponse toolCallEnd(ChatToolCallEndEvent value) { - return new V2ChatStreamResponse(new ToolCallEndValue(value)); + public static StreamedChatResponseV2 toolCallEnd(ChatToolCallEndEvent value) { + return new StreamedChatResponseV2(new ToolCallEndValue(value)); } - public static V2ChatStreamResponse citationStart(CitationStartEvent value) { - return new V2ChatStreamResponse(new CitationStartValue(value)); + public static StreamedChatResponseV2 citationStart(CitationStartEvent value) { + return new StreamedChatResponseV2(new CitationStartValue(value)); } - public static V2ChatStreamResponse citationEnd(CitationEndEvent value) { - return new V2ChatStreamResponse(new CitationEndValue(value)); + public static StreamedChatResponseV2 citationEnd(CitationEndEvent value) { + return new StreamedChatResponseV2(new CitationEndValue(value)); } - public static V2ChatStreamResponse messageEnd(ChatMessageEndEvent value) { - return new V2ChatStreamResponse(new MessageEndValue(value)); + public static StreamedChatResponseV2 messageEnd(ChatMessageEndEvent value) { + return new StreamedChatResponseV2(new MessageEndValue(value)); } - public static V2ChatStreamResponse debug(ChatDebugEvent value) { - return new V2ChatStreamResponse(new DebugValue(value)); + public static StreamedChatResponseV2 debug(ChatDebugEvent value) { + return new StreamedChatResponseV2(new DebugValue(value)); } public boolean isMessageStart() { @@ -283,7 +271,6 @@ private interface Value { } @JsonTypeName("message-start") - @JsonIgnoreProperties("type") private static final class MessageStartValue implements Value { @JsonUnwrapped private ChatMessageStartEvent value; @@ -317,12 +304,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("content-start") - @JsonIgnoreProperties("type") private static final class ContentStartValue implements Value { @JsonUnwrapped private ChatContentStartEvent value; @@ -356,12 +342,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("content-delta") - @JsonIgnoreProperties("type") private static final class ContentDeltaValue implements Value { @JsonUnwrapped private ChatContentDeltaEvent value; @@ -395,12 +380,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("content-end") - @JsonIgnoreProperties("type") private static final class ContentEndValue implements Value { @JsonUnwrapped private ChatContentEndEvent value; @@ -434,12 +418,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("tool-plan-delta") - @JsonIgnoreProperties("type") private static final class ToolPlanDeltaValue implements Value { @JsonUnwrapped private ChatToolPlanDeltaEvent value; @@ -473,12 +456,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("tool-call-start") - @JsonIgnoreProperties("type") private static final class ToolCallStartValue implements Value { @JsonUnwrapped private ChatToolCallStartEvent value; @@ -512,12 +494,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("tool-call-delta") - @JsonIgnoreProperties("type") private static final class ToolCallDeltaValue implements Value { @JsonUnwrapped private ChatToolCallDeltaEvent value; @@ -551,12 +532,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("tool-call-end") - @JsonIgnoreProperties("type") private static final class ToolCallEndValue implements Value { @JsonUnwrapped private ChatToolCallEndEvent value; @@ -590,12 +570,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("citation-start") - @JsonIgnoreProperties("type") private static final class CitationStartValue implements Value { @JsonUnwrapped private CitationStartEvent value; @@ -629,12 +608,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("citation-end") - @JsonIgnoreProperties("type") private static final class CitationEndValue implements Value { @JsonUnwrapped private CitationEndEvent value; @@ -668,12 +646,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("message-end") - @JsonIgnoreProperties("type") private static final class MessageEndValue implements Value { @JsonUnwrapped private ChatMessageEndEvent value; @@ -707,12 +684,11 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } @JsonTypeName("debug") - @JsonIgnoreProperties("type") private static final class DebugValue implements Value { @JsonUnwrapped private ChatDebugEvent value; @@ -746,11 +722,10 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "value: " + value + "}"; + return "StreamedChatResponseV2{" + "value: " + value + "}"; } } - @JsonIgnoreProperties("type") private static final class _UnknownValue implements Value { private String type; @@ -782,7 +757,7 @@ public int hashCode() { @java.lang.Override public String toString() { - return "V2ChatStreamResponse{" + "type: " + type + ", value: " + value + "}"; + return "StreamedChatResponseV2{" + "type: " + type + ", value: " + value + "}"; } } } diff --git a/src/main/java/com/cohere/api/types/SummarizeResponse.java b/src/main/java/com/cohere/api/types/SummarizeResponse.java index 6a20f22..ab07de3 100644 --- a/src/main/java/com/cohere/api/types/SummarizeResponse.java +++ b/src/main/java/com/cohere/api/types/SummarizeResponse.java @@ -109,9 +109,6 @@ public Builder from(SummarizeResponse other) { return this; } - /** - *

      Generated ID for the summary

      - */ @JsonSetter(value = "id", nulls = Nulls.SKIP) public Builder id(Optional id) { this.id = id; @@ -123,9 +120,6 @@ public Builder id(String id) { return this; } - /** - *

      Generated summary for the text

      - */ @JsonSetter(value = "summary", nulls = Nulls.SKIP) public Builder summary(Optional summary) { this.summary = summary; diff --git a/src/main/java/com/cohere/api/types/SystemMessageV2Content.java b/src/main/java/com/cohere/api/types/SystemMessageV2Content.java index ba0cf55..401daf6 100644 --- a/src/main/java/com/cohere/api/types/SystemMessageV2Content.java +++ b/src/main/java/com/cohere/api/types/SystemMessageV2Content.java @@ -31,7 +31,6 @@ public Object get() { return this.value; } - @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if (this.type == 0) { return visitor.visit((String) this.value); @@ -81,7 +80,7 @@ static final class Deserializer extends StdDeserializer } @java.lang.Override - public SystemMessageV2Content deserialize(JsonParser p, DeserializationContext context) throws IOException { + public SystemMessageV2Content deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); diff --git a/src/main/java/com/cohere/api/types/SystemMessageV2ContentItem.java b/src/main/java/com/cohere/api/types/SystemMessageV2ContentItem.java index 6fcc422..da0e9e3 100644 --- a/src/main/java/com/cohere/api/types/SystemMessageV2ContentItem.java +++ b/src/main/java/com/cohere/api/types/SystemMessageV2ContentItem.java @@ -71,7 +71,6 @@ private interface Value { } @JsonTypeName("text") - @JsonIgnoreProperties("type") private static final class TextValue implements Value { @JsonUnwrapped private ChatTextContent value; @@ -109,7 +108,6 @@ public String toString() { } } - @JsonIgnoreProperties("type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/Thinking.java b/src/main/java/com/cohere/api/types/Thinking.java new file mode 100644 index 0000000..ca5d6fe --- /dev/null +++ b/src/main/java/com/cohere/api/types/Thinking.java @@ -0,0 +1,141 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = Thinking.Builder.class) +public final class Thinking { + private final ThinkingType type; + + private final Optional tokenBudget; + + private final Map additionalProperties; + + private Thinking(ThinkingType type, Optional tokenBudget, Map additionalProperties) { + this.type = type; + this.tokenBudget = tokenBudget; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("type") + public ThinkingType getType() { + return type; + } + + /** + * @return The maximum number of tokens the model can use for thinking, which must be set to a positive integer. + * The model will stop thinking if it reaches the thinking token budget and will proceed with the response. + */ + @JsonProperty("token_budget") + public Optional getTokenBudget() { + return tokenBudget; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof Thinking && equalTo((Thinking) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(Thinking other) { + return type.equals(other.type) && tokenBudget.equals(other.tokenBudget); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.type, this.tokenBudget); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TypeStage builder() { + return new Builder(); + } + + public interface TypeStage { + _FinalStage type(@NotNull ThinkingType type); + + Builder from(Thinking other); + } + + public interface _FinalStage { + Thinking build(); + + _FinalStage tokenBudget(Optional tokenBudget); + + _FinalStage tokenBudget(Integer tokenBudget); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TypeStage, _FinalStage { + private ThinkingType type; + + private Optional tokenBudget = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(Thinking other) { + type(other.getType()); + tokenBudget(other.getTokenBudget()); + return this; + } + + @java.lang.Override + @JsonSetter("type") + public _FinalStage type(@NotNull ThinkingType type) { + this.type = Objects.requireNonNull(type, "type must not be null"); + return this; + } + + /** + *

      The maximum number of tokens the model can use for thinking, which must be set to a positive integer. + * The model will stop thinking if it reaches the thinking token budget and will proceed with the response.

      + * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage tokenBudget(Integer tokenBudget) { + this.tokenBudget = Optional.ofNullable(tokenBudget); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_budget", nulls = Nulls.SKIP) + public _FinalStage tokenBudget(Optional tokenBudget) { + this.tokenBudget = tokenBudget; + return this; + } + + @java.lang.Override + public Thinking build() { + return new Thinking(type, tokenBudget, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/types/ReasoningEffort.java b/src/main/java/com/cohere/api/types/ThinkingType.java similarity index 72% rename from src/main/java/com/cohere/api/types/ReasoningEffort.java rename to src/main/java/com/cohere/api/types/ThinkingType.java index ea7b528..dff8242 100644 --- a/src/main/java/com/cohere/api/types/ReasoningEffort.java +++ b/src/main/java/com/cohere/api/types/ThinkingType.java @@ -5,16 +5,14 @@ import com.fasterxml.jackson.annotation.JsonValue; -public enum ReasoningEffort { - LOW("low"), +public enum ThinkingType { + ENABLED("enabled"), - MEDIUM("medium"), - - HIGH("high"); + DISABLED("disabled"); private final String value; - ReasoningEffort(String value) { + ThinkingType(String value) { this.value = value; } diff --git a/src/main/java/com/cohere/api/types/TokenizeResponse.java b/src/main/java/com/cohere/api/types/TokenizeResponse.java index 031661e..a6c9279 100644 --- a/src/main/java/com/cohere/api/types/TokenizeResponse.java +++ b/src/main/java/com/cohere/api/types/TokenizeResponse.java @@ -108,9 +108,6 @@ public Builder from(TokenizeResponse other) { return this; } - /** - *

      An array of tokens, where each token is an integer.

      - */ @JsonSetter(value = "tokens", nulls = Nulls.SKIP) public Builder tokens(List tokens) { this.tokens.clear(); diff --git a/src/main/java/com/cohere/api/types/Tool.java b/src/main/java/com/cohere/api/types/Tool.java index 80c03fa..29b7b3b 100644 --- a/src/main/java/com/cohere/api/types/Tool.java +++ b/src/main/java/com/cohere/api/types/Tool.java @@ -104,35 +104,18 @@ public static NameStage builder() { } public interface NameStage { - /** - *

      The name of the tool to be called. Valid names contain only the characters a-z, A-Z, 0-9, _ and must not begin with a digit.

      - */ DescriptionStage name(@NotNull String name); Builder from(Tool other); } public interface DescriptionStage { - /** - *

      The description of what the tool does, the model uses the description to choose when and how to call the function.

      - */ _FinalStage description(@NotNull String description); } public interface _FinalStage { Tool build(); - /** - *

      The input parameters of the tool. Accepts a dictionary where the key is the name of the parameter and the value is the parameter spec. Valid parameter names contain only the characters a-z, A-Z, 0-9, _ and must not begin with a digit.

      - *
      {
      -         *   "my_param": {
      -         *     "description": <string>,
      -         *     "type": <string>, // any python data type, such as 'str', 'bool'
      -         *     "required": <boolean>
      -         *   }
      -         * }
      -         * 
      - */ _FinalStage parameterDefinitions(Optional> parameterDefinitions); _FinalStage parameterDefinitions(Map parameterDefinitions); @@ -160,7 +143,6 @@ public Builder from(Tool other) { } /** - *

      The name of the tool to be called. Valid names contain only the characters a-z, A-Z, 0-9, _ and must not begin with a digit.

      *

      The name of the tool to be called. Valid names contain only the characters a-z, A-Z, 0-9, _ and must not begin with a digit.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -172,7 +154,6 @@ public DescriptionStage name(@NotNull String name) { } /** - *

      The description of what the tool does, the model uses the description to choose when and how to call the function.

      *

      The description of what the tool does, the model uses the description to choose when and how to call the function.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -201,17 +182,6 @@ public _FinalStage parameterDefinitions(MapThe input parameters of the tool. Accepts a dictionary where the key is the name of the parameter and the value is the parameter spec. Valid parameter names contain only the characters a-z, A-Z, 0-9, _ and must not begin with a digit.

      - *
      {
      -         *   "my_param": {
      -         *     "description": <string>,
      -         *     "type": <string>, // any python data type, such as 'str', 'bool'
      -         *     "required": <boolean>
      -         *   }
      -         * }
      -         * 
      - */ @java.lang.Override @JsonSetter(value = "parameter_definitions", nulls = Nulls.SKIP) public _FinalStage parameterDefinitions( diff --git a/src/main/java/com/cohere/api/types/ToolCall.java b/src/main/java/com/cohere/api/types/ToolCall.java index 3805f60..d8c10f9 100644 --- a/src/main/java/com/cohere/api/types/ToolCall.java +++ b/src/main/java/com/cohere/api/types/ToolCall.java @@ -79,9 +79,6 @@ public static NameStage builder() { } public interface NameStage { - /** - *

      Name of the tool to call.

      - */ _FinalStage name(@NotNull String name); Builder from(ToolCall other); @@ -90,9 +87,6 @@ public interface NameStage { public interface _FinalStage { ToolCall build(); - /** - *

      The name and value of the parameters to use when invoking a tool.

      - */ _FinalStage parameters(Map parameters); _FinalStage putAllParameters(Map parameters); @@ -119,7 +113,6 @@ public Builder from(ToolCall other) { } /** - *

      Name of the tool to call.

      *

      Name of the tool to call.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -150,9 +143,6 @@ public _FinalStage putAllParameters(Map parameters) { return this; } - /** - *

      The name and value of the parameters to use when invoking a tool.

      - */ @java.lang.Override @JsonSetter(value = "parameters", nulls = Nulls.SKIP) public _FinalStage parameters(Map parameters) { diff --git a/src/main/java/com/cohere/api/types/ToolCallDelta.java b/src/main/java/com/cohere/api/types/ToolCallDelta.java index b31588d..7005743 100644 --- a/src/main/java/com/cohere/api/types/ToolCallDelta.java +++ b/src/main/java/com/cohere/api/types/ToolCallDelta.java @@ -130,9 +130,6 @@ public Builder from(ToolCallDelta other) { return this; } - /** - *

      Name of the tool call

      - */ @JsonSetter(value = "name", nulls = Nulls.SKIP) public Builder name(Optional name) { this.name = name; @@ -144,9 +141,6 @@ public Builder name(String name) { return this; } - /** - *

      Index of the tool call generated

      - */ @JsonSetter(value = "index", nulls = Nulls.SKIP) public Builder index(Optional index) { this.index = index; @@ -158,9 +152,6 @@ public Builder index(Double index) { return this; } - /** - *

      Chunk of the tool parameters

      - */ @JsonSetter(value = "parameters", nulls = Nulls.SKIP) public Builder parameters(Optional parameters) { this.parameters = parameters; @@ -172,9 +163,6 @@ public Builder parameters(String parameters) { return this; } - /** - *

      Chunk of the tool plan text

      - */ @JsonSetter(value = "text", nulls = Nulls.SKIP) public Builder text(Optional text) { this.text = text; diff --git a/src/main/java/com/cohere/api/types/ToolContent.java b/src/main/java/com/cohere/api/types/ToolContent.java index d23533a..0d2459f 100644 --- a/src/main/java/com/cohere/api/types/ToolContent.java +++ b/src/main/java/com/cohere/api/types/ToolContent.java @@ -88,7 +88,6 @@ private interface Value { } @JsonTypeName("text") - @JsonIgnoreProperties("type") private static final class TextValue implements Value { @JsonUnwrapped private ChatTextContent value; @@ -127,7 +126,6 @@ public String toString() { } @JsonTypeName("document") - @JsonIgnoreProperties("type") private static final class DocumentValue implements Value { @JsonUnwrapped private DocumentContent value; @@ -165,7 +163,6 @@ public String toString() { } } - @JsonIgnoreProperties("type") private static final class _UnknownValue implements Value { private String type; diff --git a/src/main/java/com/cohere/api/types/ToolMessageV2.java b/src/main/java/com/cohere/api/types/ToolMessageV2.java index c1ccff6..581d115 100644 --- a/src/main/java/com/cohere/api/types/ToolMessageV2.java +++ b/src/main/java/com/cohere/api/types/ToolMessageV2.java @@ -77,18 +77,12 @@ public static ToolCallIdStage builder() { } public interface ToolCallIdStage { - /** - *

      The id of the associated tool call that has provided the given content

      - */ ContentStage toolCallId(@NotNull String toolCallId); Builder from(ToolMessageV2 other); } public interface ContentStage { - /** - *

      Outputs from a tool. The content should formatted as a JSON object string, or a list of tool content blocks

      - */ _FinalStage content(@NotNull ToolMessageV2Content content); } @@ -115,7 +109,6 @@ public Builder from(ToolMessageV2 other) { } /** - *

      The id of the associated tool call that has provided the given content

      *

      The id of the associated tool call that has provided the given content

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -127,7 +120,6 @@ public ContentStage toolCallId(@NotNull String toolCallId) { } /** - *

      Outputs from a tool. The content should formatted as a JSON object string, or a list of tool content blocks

      *

      Outputs from a tool. The content should formatted as a JSON object string, or a list of tool content blocks

      * @return Reference to {@code this} so that method calls can be chained together. */ diff --git a/src/main/java/com/cohere/api/types/ToolMessageV2Content.java b/src/main/java/com/cohere/api/types/ToolMessageV2Content.java index 67b1e9f..fdfe1ce 100644 --- a/src/main/java/com/cohere/api/types/ToolMessageV2Content.java +++ b/src/main/java/com/cohere/api/types/ToolMessageV2Content.java @@ -31,7 +31,6 @@ public Object get() { return this.value; } - @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if (this.type == 0) { return visitor.visit((String) this.value); @@ -81,7 +80,7 @@ static final class Deserializer extends StdDeserializer { } @java.lang.Override - public ToolMessageV2Content deserialize(JsonParser p, DeserializationContext context) throws IOException { + public ToolMessageV2Content deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); diff --git a/src/main/java/com/cohere/api/types/ToolParameterDefinitionsValue.java b/src/main/java/com/cohere/api/types/ToolParameterDefinitionsValue.java index 502079b..472feda 100644 --- a/src/main/java/com/cohere/api/types/ToolParameterDefinitionsValue.java +++ b/src/main/java/com/cohere/api/types/ToolParameterDefinitionsValue.java @@ -94,9 +94,6 @@ public static TypeStage builder() { } public interface TypeStage { - /** - *

      The type of the parameter. Must be a valid Python type.

      - */ _FinalStage type(@NotNull String type); Builder from(ToolParameterDefinitionsValue other); @@ -105,16 +102,10 @@ public interface TypeStage { public interface _FinalStage { ToolParameterDefinitionsValue build(); - /** - *

      The description of the parameter.

      - */ _FinalStage description(Optional description); _FinalStage description(String description); - /** - *

      Denotes whether the parameter is always present (required) or not. Defaults to not required.

      - */ _FinalStage required(Optional required); _FinalStage required(Boolean required); @@ -142,7 +133,6 @@ public Builder from(ToolParameterDefinitionsValue other) { } /** - *

      The type of the parameter. Must be a valid Python type.

      *

      The type of the parameter. Must be a valid Python type.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -163,9 +153,6 @@ public _FinalStage required(Boolean required) { return this; } - /** - *

      Denotes whether the parameter is always present (required) or not. Defaults to not required.

      - */ @java.lang.Override @JsonSetter(value = "required", nulls = Nulls.SKIP) public _FinalStage required(Optional required) { @@ -183,9 +170,6 @@ public _FinalStage description(String description) { return this; } - /** - *

      The description of the parameter.

      - */ @java.lang.Override @JsonSetter(value = "description", nulls = Nulls.SKIP) public _FinalStage description(Optional description) { diff --git a/src/main/java/com/cohere/api/types/ToolV2.java b/src/main/java/com/cohere/api/types/ToolV2.java index 38c6063..ab47864 100644 --- a/src/main/java/com/cohere/api/types/ToolV2.java +++ b/src/main/java/com/cohere/api/types/ToolV2.java @@ -102,9 +102,6 @@ public Builder type(String type) { return this; } - /** - *

      The function to be executed.

      - */ @JsonSetter(value = "function", nulls = Nulls.SKIP) public Builder function(Optional function) { this.function = function; diff --git a/src/main/java/com/cohere/api/types/ToolV2Function.java b/src/main/java/com/cohere/api/types/ToolV2Function.java index 9af8fac..3d68ddd 100644 --- a/src/main/java/com/cohere/api/types/ToolV2Function.java +++ b/src/main/java/com/cohere/api/types/ToolV2Function.java @@ -95,9 +95,6 @@ public static NameStage builder() { } public interface NameStage { - /** - *

      The name of the function.

      - */ _FinalStage name(@NotNull String name); Builder from(ToolV2Function other); @@ -106,16 +103,10 @@ public interface NameStage { public interface _FinalStage { ToolV2Function build(); - /** - *

      The description of the function.

      - */ _FinalStage description(Optional description); _FinalStage description(String description); - /** - *

      The parameters of the function as a JSON schema.

      - */ _FinalStage parameters(Map parameters); _FinalStage putAllParameters(Map parameters); @@ -145,7 +136,6 @@ public Builder from(ToolV2Function other) { } /** - *

      The name of the function.

      *

      The name of the function.

      * @return Reference to {@code this} so that method calls can be chained together. */ @@ -176,9 +166,6 @@ public _FinalStage putAllParameters(Map parameters) { return this; } - /** - *

      The parameters of the function as a JSON schema.

      - */ @java.lang.Override @JsonSetter(value = "parameters", nulls = Nulls.SKIP) public _FinalStage parameters(Map parameters) { @@ -197,9 +184,6 @@ public _FinalStage description(String description) { return this; } - /** - *

      The description of the function.

      - */ @java.lang.Override @JsonSetter(value = "description", nulls = Nulls.SKIP) public _FinalStage description(Optional description) { diff --git a/src/main/java/com/cohere/api/types/TruncationStrategy.java b/src/main/java/com/cohere/api/types/TruncationStrategy.java new file mode 100644 index 0000000..90982a1 --- /dev/null +++ b/src/main/java/com/cohere/api/types/TruncationStrategy.java @@ -0,0 +1,200 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonUnwrapped; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.Objects; +import java.util.Optional; + +public final class TruncationStrategy { + private final Value value; + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + private TruncationStrategy(Value value) { + this.value = value; + } + + public T visit(Visitor visitor) { + return value.visit(visitor); + } + + public static TruncationStrategy auto(TruncationStrategyAutoPreserveOrder value) { + return new TruncationStrategy(new AutoValue(value)); + } + + public static TruncationStrategy none(TruncationStrategyNone value) { + return new TruncationStrategy(new NoneValue(value)); + } + + public boolean isAuto() { + return value instanceof AutoValue; + } + + public boolean isNone() { + return value instanceof NoneValue; + } + + public boolean _isUnknown() { + return value instanceof _UnknownValue; + } + + public Optional getAuto() { + if (isAuto()) { + return Optional.of(((AutoValue) value).value); + } + return Optional.empty(); + } + + public Optional getNone() { + if (isNone()) { + return Optional.of(((NoneValue) value).value); + } + return Optional.empty(); + } + + public Optional _getUnknown() { + if (_isUnknown()) { + return Optional.of(((_UnknownValue) value).value); + } + return Optional.empty(); + } + + @JsonValue + private Value getValue() { + return this.value; + } + + public interface Visitor { + T visitAuto(TruncationStrategyAutoPreserveOrder auto); + + T visitNone(TruncationStrategyNone none); + + T _visitUnknown(Object unknownType); + } + + @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", visible = true, defaultImpl = _UnknownValue.class) + @JsonSubTypes({@JsonSubTypes.Type(AutoValue.class), @JsonSubTypes.Type(NoneValue.class)}) + @JsonIgnoreProperties(ignoreUnknown = true) + private interface Value { + T visit(Visitor visitor); + } + + @JsonTypeName("auto") + private static final class AutoValue implements Value { + @JsonUnwrapped + private TruncationStrategyAutoPreserveOrder value; + + @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) + private AutoValue() {} + + private AutoValue(TruncationStrategyAutoPreserveOrder value) { + this.value = value; + } + + @java.lang.Override + public T visit(Visitor visitor) { + return visitor.visitAuto(value); + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AutoValue && equalTo((AutoValue) other); + } + + private boolean equalTo(AutoValue other) { + return value.equals(other.value); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value); + } + + @java.lang.Override + public String toString() { + return "TruncationStrategy{" + "value: " + value + "}"; + } + } + + @JsonTypeName("none") + private static final class NoneValue implements Value { + @JsonUnwrapped + private TruncationStrategyNone value; + + @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) + private NoneValue() {} + + private NoneValue(TruncationStrategyNone value) { + this.value = value; + } + + @java.lang.Override + public T visit(Visitor visitor) { + return visitor.visitNone(value); + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof NoneValue && equalTo((NoneValue) other); + } + + private boolean equalTo(NoneValue other) { + return value.equals(other.value); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value); + } + + @java.lang.Override + public String toString() { + return "TruncationStrategy{" + "value: " + value + "}"; + } + } + + private static final class _UnknownValue implements Value { + private String type; + + @JsonValue + private Object value; + + @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) + private _UnknownValue(@JsonProperty("value") Object value) {} + + @java.lang.Override + public T visit(Visitor visitor) { + return visitor._visitUnknown(value); + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof _UnknownValue && equalTo((_UnknownValue) other); + } + + private boolean equalTo(_UnknownValue other) { + return type.equals(other.type) && value.equals(other.value); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.type, this.value); + } + + @java.lang.Override + public String toString() { + return "TruncationStrategy{" + "type: " + type + ", value: " + value + "}"; + } + } +} diff --git a/src/main/java/com/cohere/api/types/TruncationStrategyAutoPreserveOrder.java b/src/main/java/com/cohere/api/types/TruncationStrategyAutoPreserveOrder.java new file mode 100644 index 0000000..d02f473 --- /dev/null +++ b/src/main/java/com/cohere/api/types/TruncationStrategyAutoPreserveOrder.java @@ -0,0 +1,59 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TruncationStrategyAutoPreserveOrder.Builder.class) +public final class TruncationStrategyAutoPreserveOrder { + private final Map additionalProperties; + + private TruncationStrategyAutoPreserveOrder(Map additionalProperties) { + this.additionalProperties = additionalProperties; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TruncationStrategyAutoPreserveOrder; + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(TruncationStrategyAutoPreserveOrder other) { + return this; + } + + public TruncationStrategyAutoPreserveOrder build() { + return new TruncationStrategyAutoPreserveOrder(additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/types/TruncationStrategyNone.java b/src/main/java/com/cohere/api/types/TruncationStrategyNone.java new file mode 100644 index 0000000..1112730 --- /dev/null +++ b/src/main/java/com/cohere/api/types/TruncationStrategyNone.java @@ -0,0 +1,59 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TruncationStrategyNone.Builder.class) +public final class TruncationStrategyNone { + private final Map additionalProperties; + + private TruncationStrategyNone(Map additionalProperties) { + this.additionalProperties = additionalProperties; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TruncationStrategyNone; + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(TruncationStrategyNone other) { + return this; + } + + public TruncationStrategyNone build() { + return new TruncationStrategyNone(additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/types/UsageBilledUnits.java b/src/main/java/com/cohere/api/types/UsageBilledUnits.java index edacc1a..681ffab 100644 --- a/src/main/java/com/cohere/api/types/UsageBilledUnits.java +++ b/src/main/java/com/cohere/api/types/UsageBilledUnits.java @@ -130,9 +130,6 @@ public Builder from(UsageBilledUnits other) { return this; } - /** - *

      The number of billed input tokens.

      - */ @JsonSetter(value = "input_tokens", nulls = Nulls.SKIP) public Builder inputTokens(Optional inputTokens) { this.inputTokens = inputTokens; @@ -144,9 +141,6 @@ public Builder inputTokens(Double inputTokens) { return this; } - /** - *

      The number of billed output tokens.

      - */ @JsonSetter(value = "output_tokens", nulls = Nulls.SKIP) public Builder outputTokens(Optional outputTokens) { this.outputTokens = outputTokens; @@ -158,9 +152,6 @@ public Builder outputTokens(Double outputTokens) { return this; } - /** - *

      The number of billed search units.

      - */ @JsonSetter(value = "search_units", nulls = Nulls.SKIP) public Builder searchUnits(Optional searchUnits) { this.searchUnits = searchUnits; @@ -172,9 +163,6 @@ public Builder searchUnits(Double searchUnits) { return this; } - /** - *

      The number of billed classifications units.

      - */ @JsonSetter(value = "classifications", nulls = Nulls.SKIP) public Builder classifications(Optional classifications) { this.classifications = classifications; diff --git a/src/main/java/com/cohere/api/types/UsageTokens.java b/src/main/java/com/cohere/api/types/UsageTokens.java index 1dc85d5..6d4cc92 100644 --- a/src/main/java/com/cohere/api/types/UsageTokens.java +++ b/src/main/java/com/cohere/api/types/UsageTokens.java @@ -95,9 +95,6 @@ public Builder from(UsageTokens other) { return this; } - /** - *

      The number of tokens used as input to the model.

      - */ @JsonSetter(value = "input_tokens", nulls = Nulls.SKIP) public Builder inputTokens(Optional inputTokens) { this.inputTokens = inputTokens; @@ -109,9 +106,6 @@ public Builder inputTokens(Double inputTokens) { return this; } - /** - *

      The number of tokens produced by the model.

      - */ @JsonSetter(value = "output_tokens", nulls = Nulls.SKIP) public Builder outputTokens(Optional outputTokens) { this.outputTokens = outputTokens; diff --git a/src/main/java/com/cohere/api/types/UserMessageV2.java b/src/main/java/com/cohere/api/types/UserMessageV2.java index abae658..e92da1b 100644 --- a/src/main/java/com/cohere/api/types/UserMessageV2.java +++ b/src/main/java/com/cohere/api/types/UserMessageV2.java @@ -67,10 +67,6 @@ public static ContentStage builder() { } public interface ContentStage { - /** - *

      The content of the message. This can be a string or a list of content blocks. - * If a string is provided, it will be treated as a text content block.

      - */ _FinalStage content(@NotNull UserMessageV2Content content); Builder from(UserMessageV2 other); @@ -96,8 +92,6 @@ public Builder from(UserMessageV2 other) { } /** - *

      The content of the message. This can be a string or a list of content blocks. - * If a string is provided, it will be treated as a text content block.

      *

      The content of the message. This can be a string or a list of content blocks. * If a string is provided, it will be treated as a text content block.

      * @return Reference to {@code this} so that method calls can be chained together. diff --git a/src/main/java/com/cohere/api/types/UserMessageV2Content.java b/src/main/java/com/cohere/api/types/UserMessageV2Content.java index 3862999..ed961ac 100644 --- a/src/main/java/com/cohere/api/types/UserMessageV2Content.java +++ b/src/main/java/com/cohere/api/types/UserMessageV2Content.java @@ -31,7 +31,6 @@ public Object get() { return this.value; } - @SuppressWarnings("unchecked") public T visit(Visitor visitor) { if (this.type == 0) { return visitor.visit((String) this.value); @@ -81,7 +80,7 @@ static final class Deserializer extends StdDeserializer { } @java.lang.Override - public UserMessageV2Content deserialize(JsonParser p, DeserializationContext context) throws IOException { + public UserMessageV2Content deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); diff --git a/src/test/java/com/cohere/api/StreamTest.java b/src/test/java/com/cohere/api/StreamTest.java deleted file mode 100644 index 4de3538..0000000 --- a/src/test/java/com/cohere/api/StreamTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api; - -import static org.junit.jupiter.api.Assertions.*; - -import com.cohere.api.core.ObjectMappers; -import com.cohere.api.core.Stream; -import java.io.IOException; -import java.io.StringReader; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import org.junit.jupiter.api.Test; - -public final class StreamTest { - @Test - public void testJsonStream() { - List messages = List.of(Map.of("message", "hello"), Map.of("message", "world")); - List jsonStrings = messages.stream().map(StreamTest::mapToJson).collect(Collectors.toList()); - String input = String.join("\n", jsonStrings); - StringReader jsonInput = new StringReader(input); - Stream jsonStream = Stream.fromJson(Map.class, jsonInput); - int expectedMessages = 2; - int actualMessages = 0; - for (Map jsonObject : jsonStream) { - actualMessages++; - assertTrue(jsonObject.containsKey("message")); - } - assertEquals(expectedMessages, actualMessages); - } - - @Test - public void testSseStream() { - List events = List.of(Map.of("event", "start"), Map.of("event", "end")); - List sseStrings = events.stream().map(StreamTest::mapToSse).collect(Collectors.toList()); - String input = String.join("\n" + "\n", sseStrings); - StringReader sseInput = new StringReader(input); - Stream sseStream = Stream.fromSse(Map.class, sseInput); - int expectedEvents = 2; - int actualEvents = 0; - for (Map eventData : sseStream) { - actualEvents++; - assertTrue(eventData.containsKey("event")); - } - assertEquals(expectedEvents, actualEvents); - } - - @Test - public void testSseStreamWithTerminator() { - List events = List.of(Map.of("message", "first"), Map.of("message", "second")); - List sseStrings = events.stream().map(StreamTest::mapToSse).collect(Collectors.toList()); - sseStrings.add("data: [DONE]"); - String input = String.join("\n" + "\n", sseStrings); - StringReader sseInput = new StringReader(input); - Stream sseStream = Stream.fromSse(Map.class, sseInput, "[DONE]"); - int expectedEvents = 2; - int actualEvents = 0; - for (Map eventData : sseStream) { - actualEvents++; - assertTrue(eventData.containsKey("message")); - } - assertEquals(expectedEvents, actualEvents); - } - - @Test - public void testStreamResourceManagement() throws IOException { - StringReader testInput = new StringReader("{\"test\":\"data\"}"); - Stream testStream = Stream.fromJson(Map.class, testInput); - testStream.close(); - assertFalse(testStream.iterator().hasNext()); - } - - private static String mapToJson(Map map) { - try { - return ObjectMappers.JSON_MAPPER.writeValueAsString(map); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static String mapToSse(Map map) { - return "data: " + mapToJson(map); - } -} diff --git a/src/test/java/com/cohere/api/core/QueryStringMapperTest.java b/src/test/java/com/cohere/api/core/QueryStringMapperTest.java deleted file mode 100644 index c477854..0000000 --- a/src/test/java/com/cohere/api/core/QueryStringMapperTest.java +++ /dev/null @@ -1,339 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.cohere.api.core; - -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import okhttp3.HttpUrl; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public final class QueryStringMapperTest { - @Test - public void testObjectWithQuotedString_indexedArrays() { - Map map = new HashMap() { - { - put("hello", "\"world\""); - } - }; - - String expectedQueryString = "withquoted%5Bhello%5D=%22world%22"; - - String actualQueryString = queryString( - new HashMap() { - { - put("withquoted", map); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectWithQuotedString_arraysAsRepeats() { - Map map = new HashMap() { - { - put("hello", "\"world\""); - } - }; - - String expectedQueryString = "withquoted%5Bhello%5D=%22world%22"; - - String actualQueryString = queryString( - new HashMap() { - { - put("withquoted", map); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObject_indexedArrays() { - Map map = new HashMap() { - { - put("foo", "bar"); - put("baz", "qux"); - } - }; - - String expectedQueryString = "metadata%5Bfoo%5D=bar&metadata%5Bbaz%5D=qux"; - - String actualQueryString = queryString( - new HashMap() { - { - put("metadata", map); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObject_arraysAsRepeats() { - Map map = new HashMap() { - { - put("foo", "bar"); - put("baz", "qux"); - } - }; - - String expectedQueryString = "metadata%5Bfoo%5D=bar&metadata%5Bbaz%5D=qux"; - - String actualQueryString = queryString( - new HashMap() { - { - put("metadata", map); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testNestedObject_indexedArrays() { - Map> nestedMap = new HashMap>() { - { - put("mapkey1", new HashMap() { - { - put("mapkey1mapkey1", "mapkey1mapkey1value"); - put("mapkey1mapkey2", "mapkey1mapkey2value"); - } - }); - put("mapkey2", new HashMap() { - { - put("mapkey2mapkey1", "mapkey2mapkey1value"); - } - }); - } - }; - - String expectedQueryString = - "nested%5Bmapkey2%5D%5Bmapkey2mapkey1%5D=mapkey2mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey1" - + "%5D=mapkey1mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey2%5D=mapkey1mapkey2value"; - - String actualQueryString = queryString( - new HashMap() { - { - put("nested", nestedMap); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testNestedObject_arraysAsRepeats() { - Map> nestedMap = new HashMap>() { - { - put("mapkey1", new HashMap() { - { - put("mapkey1mapkey1", "mapkey1mapkey1value"); - put("mapkey1mapkey2", "mapkey1mapkey2value"); - } - }); - put("mapkey2", new HashMap() { - { - put("mapkey2mapkey1", "mapkey2mapkey1value"); - } - }); - } - }; - - String expectedQueryString = - "nested%5Bmapkey2%5D%5Bmapkey2mapkey1%5D=mapkey2mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey1" - + "%5D=mapkey1mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey2%5D=mapkey1mapkey2value"; - - String actualQueryString = queryString( - new HashMap() { - { - put("nested", nestedMap); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testDateTime_indexedArrays() { - OffsetDateTime dateTime = - OffsetDateTime.ofInstant(Instant.ofEpochSecond(1740412107L), ZoneId.of("America/New_York")); - - String expectedQueryString = "datetime=2025-02-24T10%3A48%3A27-05%3A00"; - - String actualQueryString = queryString( - new HashMap() { - { - put("datetime", dateTime); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testDateTime_arraysAsRepeats() { - OffsetDateTime dateTime = - OffsetDateTime.ofInstant(Instant.ofEpochSecond(1740412107L), ZoneId.of("America/New_York")); - - String expectedQueryString = "datetime=2025-02-24T10%3A48%3A27-05%3A00"; - - String actualQueryString = queryString( - new HashMap() { - { - put("datetime", dateTime); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectArray_indexedArrays() { - List> mapArray = new ArrayList>() { - { - add(new HashMap() { - { - put("key", "hello"); - put("value", "world"); - } - }); - add(new HashMap() { - { - put("key", "foo"); - put("value", "bar"); - } - }); - add(new HashMap<>()); - } - }; - - String expectedQueryString = "objects%5B0%5D%5Bvalue%5D=world&objects%5B0%5D%5Bkey%5D=hello&objects%5B1%5D" - + "%5Bvalue%5D=bar&objects%5B1%5D%5Bkey%5D=foo"; - - String actualQueryString = queryString( - new HashMap() { - { - put("objects", mapArray); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectArray_arraysAsRepeats() { - List> mapArray = new ArrayList>() { - { - add(new HashMap() { - { - put("key", "hello"); - put("value", "world"); - } - }); - add(new HashMap() { - { - put("key", "foo"); - put("value", "bar"); - } - }); - add(new HashMap<>()); - } - }; - - String expectedQueryString = - "objects%5Bvalue%5D=world&objects%5Bkey%5D=hello&objects%5Bvalue" + "%5D=bar&objects%5Bkey%5D=foo"; - - String actualQueryString = queryString( - new HashMap() { - { - put("objects", mapArray); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectWithArray_indexedArrays() { - Map objectWithArray = new HashMap() { - { - put("id", "abc123"); - put("contactIds", new ArrayList() { - { - add("id1"); - add("id2"); - add("id3"); - } - }); - } - }; - - String expectedQueryString = - "objectwitharray%5Bid%5D=abc123&objectwitharray%5BcontactIds%5D%5B0%5D=id1&objectwitharray" - + "%5BcontactIds%5D%5B1%5D=id2&objectwitharray%5BcontactIds%5D%5B2%5D=id3"; - - String actualQueryString = queryString( - new HashMap() { - { - put("objectwitharray", objectWithArray); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectWithArray_arraysAsRepeats() { - Map objectWithArray = new HashMap() { - { - put("id", "abc123"); - put("contactIds", new ArrayList() { - { - add("id1"); - add("id2"); - add("id3"); - } - }); - } - }; - - String expectedQueryString = "objectwitharray%5Bid%5D=abc123&objectwitharray%5BcontactIds" - + "%5D=id1&objectwitharray%5BcontactIds%5D=id2&objectwitharray%5BcontactIds%5D=id3"; - - String actualQueryString = queryString( - new HashMap() { - { - put("objectwitharray", objectWithArray); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - private static String queryString(Map params, boolean arraysAsRepeats) { - HttpUrl.Builder httpUrl = HttpUrl.parse("http://www.fakewebsite.com/").newBuilder(); - params.forEach((paramName, paramValue) -> - QueryStringMapper.addQueryParameter(httpUrl, paramName, paramValue, arraysAsRepeats)); - return httpUrl.build().encodedQuery(); - } -}