Jai — Open AI API Java Client
Introducing Jai — a simple and efficient Java client powered by Open AI
Originally published on Medium.
Introducing Jai — a simple and efficient Java client powered by Open AI

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 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 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'
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 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 simply 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 is used to print the exception's stack trace to the console. Finally, the getStatusMessage() method is used to print any status messages that 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 in a similar way to the CompletableFuture returned by the chatAsync() method.
In both methods, a ChatRequest object is created with the message "What is AI?" and the Role.USER. The Model used in the ChatRequest the 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.
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, and use it to create and invoke chat requests synchronously or asynchronously.
Jai is a minimalist Java library for the Open AI API that aims to be simple and easy to use without any unnecessary dependencies. With Jai, you can effortlessly send chat requests and receive accurate responses without complicated configurations. To learn more about Jai and how to use it, check out this article on Jai's features and goals.
Follow up links
- Java Open AI Client
- Using ChatGpt embeddings and Hyde to improve search results
- Anthropics Claude Chatbot Gets Upgrade
- Elon Musks XAi's new frontier for artificial intelligence
- Using Mockito to test JAI Java Open AI Client
- Fine-tuning journey with Open AI API
- Using Open AI to create callback functions, the basis for plugins
- Using Java Open AI Client Async
- Fastest Java JSON Parser
- Java Open AI API Client on Github