All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cohere.api.Cohere Maven / Gradle / Ivy

There is a newer version: 1.4.1
Show newest version
/**
 * This file was auto-generated by Fern from our API Definition.
 */
package com.cohere.api;

import com.cohere.api.core.ApiError;
import com.cohere.api.core.ClientOptions;
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.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.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.io.IOException;
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 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.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 Chat with Streaming and RAG follow this guide.
     */
    public Iterable chatStream(ChatStreamRequest request) {
        return chatStream(request, null);
    }

    /**
     * Generates a text response to a user message.
     * To learn how to use Chat with Streaming and RAG follow this guide.
     */
    public Iterable chatStream(ChatStreamRequest request, RequestOptions requestOptions) {
        HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl())
                .newBuilder()
                .addPathSegments("chat")
                .build();
        RequestBody body;
        try {
            body = RequestBody.create(
                    ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Request okhttpRequest = new Request.Builder()
                .url(httpUrl)
                .method("POST", body)
                .headers(Headers.of(clientOptions.headers(requestOptions)))
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            OkHttpClient client = clientOptions.httpClient();
            if (requestOptions != null && requestOptions.getTimeout().isPresent()) {
                client = clientOptions.httpClientWithTimeout(requestOptions);
            }
            Response response = client.newCall(okhttpRequest).execute();
            ResponseBody responseBody = response.body();
            if (response.isSuccessful()) {
                return new Stream(StreamedChatResponse.class, responseBody.charStream(), "\n");
            }
            throw new ApiError(
                    response.code(),
                    ObjectMappers.JSON_MAPPER.readValue(
                            responseBody != null ? responseBody.string() : "{}", Object.class));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Generates a text response to a user message.
     * To learn how to use Chat with Streaming and RAG follow this guide.
     */
    public NonStreamedChatResponse chat(ChatRequest request) {
        return chat(request, null);
    }

    /**
     * Generates a text response to a user message.
     * To learn how to use Chat with Streaming and RAG follow this guide.
     */
    public NonStreamedChatResponse chat(ChatRequest request, RequestOptions requestOptions) {
        HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl())
                .newBuilder()
                .addPathSegments("chat")
                .build();
        RequestBody body;
        try {
            body = RequestBody.create(
                    ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Request okhttpRequest = new Request.Builder()
                .url(httpUrl)
                .method("POST", body)
                .headers(Headers.of(clientOptions.headers(requestOptions)))
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            OkHttpClient client = clientOptions.httpClient();
            if (requestOptions != null && requestOptions.getTimeout().isPresent()) {
                client = clientOptions.httpClientWithTimeout(requestOptions);
            }
            Response response = client.newCall(okhttpRequest).execute();
            ResponseBody responseBody = response.body();
            if (response.isSuccessful()) {
                return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NonStreamedChatResponse.class);
            }
            throw new ApiError(
                    response.code(),
                    ObjectMappers.JSON_MAPPER.readValue(
                            responseBody != null ? responseBody.string() : "{}", Object.class));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 
* 🚧 Warning *

This API is marked as "Legacy" and is no longer maintained. Follow the migration guide to start using the Chat API.

*
*

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 to start using the Chat API.

*
*

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("generate") .build(); RequestBody body; try { body = RequestBody.create( ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); } catch (Exception e) { throw new RuntimeException(e); } Request okhttpRequest = new Request.Builder() .url(httpUrl) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") .build(); try { OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } Response response = client.newCall(okhttpRequest).execute(); ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return new Stream( GenerateStreamedResponse.class, responseBody.charStream(), "\n"); } throw new ApiError( response.code(), ObjectMappers.JSON_MAPPER.readValue( responseBody != null ? responseBody.string() : "{}", Object.class)); } catch (IOException e) { throw new RuntimeException(e); } } /** *
* 🚧 Warning *

This API is marked as "Legacy" and is no longer maintained. Follow the migration guide to start using the Chat API.

*
*

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 to start using the Chat API.

*
*

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("generate") .build(); RequestBody body; try { body = RequestBody.create( ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); } catch (Exception e) { throw new RuntimeException(e); } Request okhttpRequest = new Request.Builder() .url(httpUrl) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") .build(); try { OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } Response response = client.newCall(okhttpRequest).execute(); ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Generation.class); } throw new ApiError( response.code(), ObjectMappers.JSON_MAPPER.readValue( responseBody != null ? responseBody.string() : "{}", Object.class)); } catch (IOException e) { throw new RuntimeException(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(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("embed") .build(); RequestBody body; try { body = RequestBody.create( ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); } catch (Exception e) { throw new RuntimeException(e); } Request okhttpRequest = new Request.Builder() .url(httpUrl) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") .build(); try { OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } Response response = client.newCall(okhttpRequest).execute(); ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedResponse.class); } throw new ApiError( response.code(), ObjectMappers.JSON_MAPPER.readValue( responseBody != null ? responseBody.string() : "{}", Object.class)); } catch (IOException e) { throw new RuntimeException(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("rerank") .build(); RequestBody body; try { body = RequestBody.create( ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); } catch (Exception e) { throw new RuntimeException(e); } Request okhttpRequest = new Request.Builder() .url(httpUrl) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") .build(); try { OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } Response response = client.newCall(okhttpRequest).execute(); ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), RerankResponse.class); } throw new ApiError( response.code(), ObjectMappers.JSON_MAPPER.readValue( responseBody != null ? responseBody.string() : "{}", Object.class)); } catch (IOException e) { throw new RuntimeException(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("classify") .build(); RequestBody body; try { body = RequestBody.create( ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); } catch (Exception e) { throw new RuntimeException(e); } Request okhttpRequest = new Request.Builder() .url(httpUrl) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") .build(); try { OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } Response response = client.newCall(okhttpRequest).execute(); ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ClassifyResponse.class); } throw new ApiError( response.code(), ObjectMappers.JSON_MAPPER.readValue( responseBody != null ? responseBody.string() : "{}", Object.class)); } catch (IOException e) { throw new RuntimeException(e); } } /** *
* 🚧 Warning *

This API is marked as "Legacy" and is no longer maintained. Follow the migration guide to start using the Chat API.

*
*

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 to start using the Chat API.

*
*

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("summarize") .build(); RequestBody body; try { body = RequestBody.create( ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); } catch (Exception e) { throw new RuntimeException(e); } Request okhttpRequest = new Request.Builder() .url(httpUrl) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") .build(); try { OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } Response response = client.newCall(okhttpRequest).execute(); ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SummarizeResponse.class); } throw new ApiError( response.code(), ObjectMappers.JSON_MAPPER.readValue( responseBody != null ? responseBody.string() : "{}", Object.class)); } catch (IOException e) { throw new RuntimeException(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("tokenize") .build(); RequestBody body; try { body = RequestBody.create( ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); } catch (Exception e) { throw new RuntimeException(e); } Request okhttpRequest = new Request.Builder() .url(httpUrl) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") .build(); try { OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } Response response = client.newCall(okhttpRequest).execute(); ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TokenizeResponse.class); } throw new ApiError( response.code(), ObjectMappers.JSON_MAPPER.readValue( responseBody != null ? responseBody.string() : "{}", Object.class)); } catch (IOException e) { throw new RuntimeException(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("detokenize") .build(); RequestBody body; try { body = RequestBody.create( ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); } catch (Exception e) { throw new RuntimeException(e); } Request okhttpRequest = new Request.Builder() .url(httpUrl) .method("POST", body) .headers(Headers.of(clientOptions.headers(requestOptions))) .addHeader("Content-Type", "application/json") .build(); try { OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } Response response = client.newCall(okhttpRequest).execute(); ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DetokenizeResponse.class); } throw new ApiError( response.code(), ObjectMappers.JSON_MAPPER.readValue( responseBody != null ? responseBody.string() : "{}", Object.class)); } catch (IOException e) { throw new RuntimeException(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("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(); try { OkHttpClient client = clientOptions.httpClient(); if (requestOptions != null && requestOptions.getTimeout().isPresent()) { client = clientOptions.httpClientWithTimeout(requestOptions); } Response response = client.newCall(okhttpRequest).execute(); ResponseBody responseBody = response.body(); if (response.isSuccessful()) { return ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CheckApiKeyResponse.class); } throw new ApiError( response.code(), ObjectMappers.JSON_MAPPER.readValue( responseBody != null ? responseBody.string() : "{}", Object.class)); } catch (IOException e) { throw new RuntimeException(e); } } 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(); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy