JAI - Java AI - Java Open AI API Client

JAI - Java AI - Java Open AI API Client

JAI

Jai - Open AI API Java Client

Introducing Jai - a simple and efficient Java client for the Open AI API. We developed this client to provide a lightweight, uncomplicated option for accessing the Open AI API. With Jai, you can effortlessly send chat requests and receive accurate responses without unnecessary features.

Goals

Goals for JAI include providing a simple and easy-to-use Java client for the Open AI API without any unnecessary extras dependencies that could make it more challenging to use. And with as little learning curve as possible, so no fancy new framework to learn. Additionally, JAI aims to be lightweight and fast, allowing developers to quickly and easily integrate it into their projects.

Here is a list of goals for this project

  • Minimal dependencies
  • No surprises
  • Works sync or async but does not force developers either way
  • It does not force you to learn to use a new framework
  • It should work well in any Java environment
  • Easy to use idiomatic
  • Light-weight and small
  • Easy to learn

License

Apache 2.

Status

?? This is a new project and is still a work in progress.


JAI is a new project that is still a work in progress. This means that the project is in its early stages of development and may not have all the features the creators are planning to implement. It also implies that there could be some bugs or issues that the developers are still working on fixing. Nonetheless, JAI has clear goals and objectives for the project, which include providing a simple and easy-to-use Java client for the Open AI API with as little learning curve as possible. We also aim to make it lightweight and fast, allowing developers to quickly and easily integrate it into their projects.

JAI aims to be as straightforward as possible, with no surprises and no esoteric framework to learn. It is a minimalist Java library that is easy to use and requires no extra dependencies other than the JDK. This makes it simple to integrate into your projects without worrying about complex configurations or additional libraries.

Maven

JAI only depends on JParse for JSON parsing, with no other dependencies except the JVM.

Here are instructions on how to include your project with Maven.

<!-- See for latest version <https://mvnrepository.com/artifact/cloudurable/jparse> -->
<dependency>
    <groupId>com.cloudurable</groupId>
    <artifactId>jai</artifactId>
    <version>1.0.0</version>
</dependency>        

Gradle

Here are instructions on how to include your project with Gradle.

//See for latest version  <https://mvnrepository.com/artifact/cloudurable/jai>
implementation group: 'com.cloudurable', name: 'jai', version: '1.0.0'        

?? JAI has not yet been released, so it is not in any public maven repos.

What is JAI?

JAI simplifies the use of Open AI API in Java. It has no unnecessary dependencies and can be easily integrated into projects using Maven or Gradle. With JAI, you can make chat requests synchronously or asynchronously.

Using JAI

Create the client

// Create the client
final OpenAIClient client = OpenAIClient.builder().setApiKey(System.getenv("OPEN_AI_KEY")).build();        

Chat

Create a chat request

        // Create the chat request
        final ChatRequest chatRequest = ChatRequest.builder().setModel("gpt-3.5-turbo")
                .addMessage(Message.builder().setContent("What is AI?").setRole(Role.USER).build())
                .build();        

Invoke the client async for chat

        // Call Open AI API with chat message
client.chatAsync(chatRequest).thenAccept(response -> {
      response.getResponse().ifPresent(chatResponse -> 
                    chatResponse.getChoices().forEach(System.out::println));
      response.getException().ifPresent(Throwable::printStackTrace);
      response.getStatusMessage().ifPresent(error -> 
                  System.out.printf("status message %s %d \\n", error, 
                           response.getStatusCode().orElse(0)));
});        

Invoke the client synchronously for chat

// Call Open AI API with chat message
final ClientResponse<ChatRequest, ChatResponse> response = 
                                                      client.chat(chatRequest);

response.getResponse().ifPresent(
				chatResponse -> chatResponse.getChoices().forEach(System.out::println));
response.getException().ifPresent(Throwable::printStackTrace);
response.getStatusMessage().ifPresent(
		error -> 
			System.out.printf("status message %s %d \\\\n", error, 
                                      response.getStatusCode().orElse(0)))
        

Describe the complete chat example code listing step by step

Let's cover a complete code listing.

package com.cloudurable.jai;

import com.cloudurable.jai.model.ClientResponse;
import com.cloudurable.jai.model.chat.*;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class Main {
    public static void main(final String... args) {
        try {

            callChatExample();
            callChatExampleAsync();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    private static void callChatExampleAsync() throws Exception {

        final CountDownLatch latch = new CountDownLatch(1);

        // Create the client
        final OpenAIClient client = OpenAIClient.builder()
                    .setApiKey(System.getenv("OPEN_AI_KEY")).build();

        // Create the chat request
        final ChatRequest chatRequest = ChatRequest.builder()
                .setModel("gpt-3.5-turbo")
                .addMessage(Message.builder().setContent("What is AI?")
                .setRole(Role.USER).build())
                .build();

        // Call Open AI API with chat message
        client.chatAsync(chatRequest)
            .thenAccept(response -> {
                response.getResponse().ifPresent(chatResponse -> 
                        chatResponse.getChoices().forEach(System.out::println));
                response.getException().ifPresent(Throwable::printStackTrace);
                response.getStatusMessage().ifPresent(error -> 
                         System.out.printf("status message %s %d \\n", error, 
                                           response.getStatusCode().orElse(0)));
                latch.countDown();
        });

        latch.await(10, TimeUnit.SECONDS);
    }

    private static void callChatExample() throws Exception {
        // Create the client
        final OpenAIClient client = OpenAIClient.builder()
                     .setApiKey(System.getenv("OPEN_AI_KEY")).build();

        // Create the chat request
        final ChatRequest chatRequest = ChatRequest.builder()
                .setModel("gpt-3.5-turbo")
                .addMessage(Message.builder()
                .setContent("What is AI?").setRole(Role.USER).build())
                .build();

        // Call Open AI API with chat message
        final ClientResponse<ChatRequest, ChatResponse> response = 
                                                    client.chat(chatRequest);

        response.getResponse().ifPresent(chatResponse -> 
                        chatResponse.getChoices().forEach(System.out::println));

        response.getException().ifPresent(Throwable::printStackTrace);

        response.getStatusMessage().ifPresent(error -> 
               System.out.printf("status message %s %d \\n", error, 
                                      response.getStatusCode().orElse(0)));
    }
}        

The Main class is an example that includes a simple main() method, which calls the callChatExample() and callChatExampleAsync() methods, and catches any exceptions that may be thrown.

This code listing contains two methods, callChatExampleAsync() and callChatExample(), both of which are called in the main() method.

The callChatExampleAsync() creates a CountDownLatch, sets up an OpenAIClient with an API key, creates a ChatRequest object, and then invokes the chatAsync() method of the OpenAIClient object, passing in the ChatRequest object. The chatAsync() method returns a CompletableFuture that is handled asynchronously using the exceptionally() and thenAccept() methods. The exceptionally() method is used to handle any exceptions that may be thrown by the chatAsync() method, and the thenAccept() method is used to handle the response when it is received. If the response is successful, the getResponse() method is used to retrieve the ChatResponse object, and the getChoices() method is called on the ChatResponse object to print the choices to the console. If there is an exception, the getException() method prints the exception's stack trace to the console. Finally, the getStatusMessage() method prints any status messages the API may have returned.

The callChatExample() is similar to callChatExampleAsync(), with the key difference being that it invokes the chat() method of the OpenAIClient object synchronously rather than asynchronously. The chat() method returns a ClientResponse object, which is then handled similarly to the CompletableFuture returned by the chatAsync() method.

Both methods create a ChatRequest object with the message "What is AI?" and the Role.USER. The Model used in the ChatRequest object is "gpt-3.5-turbo", a model provided by the Open AI API.

Overall, these methods demonstrate how to use the JAI client to make chat requests to the Open AI API and how to handle the responses asynchronously or synchronously.

Next steps

  1. Add support for completions
  2. Add support for edits
  3. Add support for updates
  4. Add support for file uploads
  5. Add support for tunings
  6. Add support for text to audio
  7. Add support for audio to text
  8. Create some examples with chat streaming
  9. Create some examples with chat functions and function callbacks

We are at the start of this journey.

Conclusion

JAI is a minimalist Java library for the Open AI API, designed to be simple and easy to use without any unnecessary dependencies. It aims to be lightweight and fast, allowing developers to quickly and easily integrate it into their projects. To use JAI, you can create a client and make chat requests to the Open AI API. You can include JAI in your project using Maven or Gradle to create and invoke chat requests synchronously or asynchronously.


I would love to get your feedback.


Follow up links


要查看或添加评论,请登录

社区洞察

其他会员也浏览了