
com.cohere.api.Cohere Maven / Gradle / Ivy
Show all versions of cohere-java Show documentation
/**
* 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.CohereApiApiError;
import com.cohere.api.core.CohereApiError;
import com.cohere.api.core.MediaTypes;
import com.cohere.api.core.ObjectMappers;
import com.cohere.api.core.RequestOptions;
import com.cohere.api.core.Stream;
import com.cohere.api.core.Suppliers;
import com.cohere.api.errors.CohereApiBadRequestError;
import com.cohere.api.errors.CohereApiClientClosedRequestError;
import com.cohere.api.errors.CohereApiForbiddenError;
import com.cohere.api.errors.CohereApiGatewayTimeoutError;
import com.cohere.api.errors.CohereApiInternalServerError;
import com.cohere.api.errors.CohereApiNotFoundError;
import com.cohere.api.errors.CohereApiNotImplementedError;
import com.cohere.api.errors.CohereApiServiceUnavailableError;
import com.cohere.api.errors.CohereApiTooManyRequestsError;
import com.cohere.api.errors.CohereApiUnauthorizedError;
import com.cohere.api.errors.CohereApiUnprocessableEntityError;
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.ConnectorsClient;
import com.cohere.api.resources.datasets.DatasetsClient;
import com.cohere.api.resources.embedjobs.EmbedJobsClient;
import com.cohere.api.resources.finetuning.FinetuningClient;
import com.cohere.api.resources.models.ModelsClient;
import com.cohere.api.resources.v2.V2Client;
import com.cohere.api.types.CheckApiKeyResponse;
import com.cohere.api.types.ClassifyResponse;
import com.cohere.api.types.ClientClosedRequestErrorBody;
import com.cohere.api.types.DetokenizeResponse;
import com.cohere.api.types.EmbedResponse;
import com.cohere.api.types.GatewayTimeoutErrorBody;
import com.cohere.api.types.GenerateStreamedResponse;
import com.cohere.api.types.Generation;
import com.cohere.api.types.NonStreamedChatResponse;
import com.cohere.api.types.NotImplementedErrorBody;
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.cohere.api.types.TooManyRequestsErrorBody;
import com.cohere.api.types.UnprocessableEntityErrorBody;
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;
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 Cohere(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
this.v2Client = Suppliers.memoize(() -> new V2Client(clientOptions));
this.embedJobsClient = Suppliers.memoize(() -> new EmbedJobsClient(clientOptions));
this.datasetsClient = Suppliers.memoize(() -> new DatasetsClient(clientOptions));
this.connectorsClient = Suppliers.memoize(() -> new ConnectorsClient(clientOptions));
this.modelsClient = Suppliers.memoize(() -> new ModelsClient(clientOptions));
this.finetuningClient = Suppliers.memoize(() -> new FinetuningClient(clientOptions));
}
/**
* Generates a 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 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.
*/
public Iterable 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.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, responseBody.charStream(), "\n");
}
String responseBodyString = responseBody != null ? responseBody.string() : "{}";
try {
switch (response.code()) {
case 400:
throw new CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("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 NonStreamedChatResponse 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 NonStreamedChatResponse 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.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 CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("Network error executing HTTP request", e);
}
}
/**
* <Warning>
* This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
* </Warning>
* Generates realistic text conditioned on a given input.
*/
public Iterable generateStream(GenerateStreamRequest request) {
return generateStream(request, null);
}
/**
* <Warning>
* This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
* </Warning>
* Generates realistic text conditioned on a given input.
*/
public Iterable 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 CohereApiError("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, responseBody.charStream(), "\n");
}
String responseBodyString = responseBody != null ? responseBody.string() : "{}";
try {
switch (response.code()) {
case 400:
throw new CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("Network error executing HTTP request", e);
}
}
/**
* <Warning>
* This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
* </Warning>
* Generates realistic text conditioned on a given input.
*/
public Generation generate(GenerateRequest request) {
return generate(request, null);
}
/**
* <Warning>
* This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
* </Warning>
* Generates realistic text conditioned on a given input.
*/
public Generation 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 CohereApiError("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 CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("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 EmbedResponse embed() {
return embed(EmbedRequest.builder().build());
}
/**
* 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 EmbedResponse embed(EmbedRequest 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 EmbedResponse 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 CohereApiError("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 CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("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 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) {
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 CohereApiError("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 CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("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 ClassifyResponse 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 ClassifyResponse 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 CohereApiError("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 CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("Network error executing HTTP request", e);
}
}
/**
* <Warning>
* This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
* </Warning>
* Generates a summary in English for a given text.
*/
public SummarizeResponse summarize(SummarizeRequest request) {
return summarize(request, null);
}
/**
* <Warning>
* This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
* </Warning>
* Generates a summary in English for a given text.
*/
public SummarizeResponse 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 CohereApiError("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 CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("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 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) {
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 CohereApiError("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 CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("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 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) {
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 CohereApiError("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 CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("Network error executing HTTP request", e);
}
}
/**
* Checks that the api key in the Authorization header is valid and active
*/
public CheckApiKeyResponse checkApiKey() {
return checkApiKey(null);
}
/**
* Checks that the api key in the Authorization header is valid and active
*/
public CheckApiKeyResponse 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("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 CohereApiBadRequestError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 401:
throw new CohereApiUnauthorizedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 403:
throw new CohereApiForbiddenError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 404:
throw new CohereApiNotFoundError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 422:
throw new CohereApiUnprocessableEntityError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, UnprocessableEntityErrorBody.class));
case 429:
throw new CohereApiTooManyRequestsError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, TooManyRequestsErrorBody.class));
case 499:
throw new CohereApiClientClosedRequestError(ObjectMappers.JSON_MAPPER.readValue(
responseBodyString, ClientClosedRequestErrorBody.class));
case 500:
throw new CohereApiInternalServerError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 501:
throw new CohereApiNotImplementedError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NotImplementedErrorBody.class));
case 503:
throw new CohereApiServiceUnavailableError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
case 504:
throw new CohereApiGatewayTimeoutError(
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GatewayTimeoutErrorBody.class));
}
} catch (JsonProcessingException ignored) {
// unable to map error response, throwing generic error
}
throw new CohereApiApiError(
"Error with status code " + response.code(),
response.code(),
ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class));
} catch (IOException e) {
throw new CohereApiError("Network error executing HTTP request", e);
}
}
public V2Client v2() {
return this.v2Client.get();
}
public EmbedJobsClient embedJobs() {
return this.embedJobsClient.get();
}
public DatasetsClient datasets() {
return this.datasetsClient.get();
}
public ConnectorsClient connectors() {
return this.connectorsClient.get();
}
public ModelsClient models() {
return this.modelsClient.get();
}
public FinetuningClient finetuning() {
return this.finetuningClient.get();
}
public static CohereBuilder builder() {
return new CohereBuilder();
}
}