/simple-openai-client

A simple Java library to connect to OpenAI API

Primary LanguageJavaMIT LicenseMIT

Simple OpenAI Client

A simple Java library for seamless integration of your Java applications with OpenAI API.

Supported Endpoints

Installation

Maven

<dependency>
    <groupId>br.com.rcaneppele</groupId>
    <artifactId>simple-openai-client</artifactId>
    <version>1.0.4</version>
</dependency>

Gradle

implementation 'br.com.rcaneppele:simple-openai-client:1.0.3'

Usage

Chat Completion

var client = new OpenAIClient("YOUR_API_KEY");

var request = new ChatCompletionRequestBuilder()
    .model(OpenAIModel.GPT_4_1106_PREVIEW)
    .systemMessage("You are a Sustainable product name generator")
    .userMessage("Generate 2 products name")
    .build();

var response = client.sendChatCompletionRequest(request);

System.out.println(response);

The response is an object of type ChatCompletionResponse.

If you only need to print the generated message content:

// First choice
System.out.println(response.firstChoiceMessageContent());

// Last choice
System.out.println(response.lastChoiceMessageContent());

// All choices
response.choices().forEach(c -> System.out.println(c.messageContent()));

Chat Completion Parameters

The ChatCompletionRequestBuilder object has methods to set API Parameters:

var request = new ChatCompletionRequestBuilder()
    .model(OpenAIModel.GPT_4_1106_PREVIEW)
    .systemMessage("You are a Sustainable product name generator")
    .userMessage("Generate 2 products name")
    .n(3)
    .maxTokens(2048)
    .temperature(1.3)
    .frequencyPenalty(1.4)
    .seed(123)
    .user("user-id")
    .build();

var response = client.sendChatCompletionRequest(request);

response.choices().forEach(c -> System.out.println(c.messageContent()));

Timeout

The default OpenAI API response timeout is 15 seconds. If you need to change it:

// 30 seconds timeout
var client = new OpenAIClient("YOUR_API_KEY", 30);

// No timeout
var client = new OpenAIClient("YOUR_API_KEY", 0);

API Key

To send requests, generate an API KEY

ATTENTION! The API key is sensitive and confidential information; do not use it directly in your code. Instead, use Environment Variables to protect your key:

// Assuming you have an environment variable named OPENAI_API_KEY
var apiKey = System.getenv("OPENAI_API_KEY");
var client = new OpenAIClient(apiKey);

Streaming

If you require Streaming support, you can use the library as shown below:

var request = new ChatCompletionRequestBuilder()
    .model(OpenAIModel.GPT_4_1106_PREVIEW)
    .systemMessage("You are a Sustainable product name generator")
    .userMessage("Generate 2 products name")
    .build();

client.sendStreamChatCompletionRequest(request).subscribe(response ->
    {
        var message = response.firstChoiceMessageContent();
        if (message != null) {
            System.out.println(message);
        }
    });

Optionally, you can listen to events such as errors and completion during streaming:

client.sendStreamChatCompletionRequest(request).subscribe(response ->
    {
        var message = response.firstChoiceMessageContent();
        if (message != null) {
            System.out.println(message);
        }
    }, error -> {
        System.out.println("Error during streaming: " +error.getMessage());
    }, () -> {
        System.out.println("Streaming completed");
    });