Introduction

This post shows a straightforward example of how to call ChatGPT from Java.
You can use it to generate any content you like.

Getting an API Key

You will need an API key to call the service. This can be found in your account at this link.

https://platform.openai.com/account/api-keys

Example

The example below will ask it to perform the simple task of listing the top ten most popular programming languages.

First, include the library from here
https://github.com/TheoKanning/openai-java

<dependency>
  <groupId>com.theokanning.openai-gpt3-java</groupId>
  <artifactId>service</artifactId>
  <version>0.12.0</version>
</dependency>

Then we can write a simple test to make the call.

import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import org.junit.jupiter.api.Test;

public class ChatGptTest {

    private static final String TOKEN = "API_KEY";
    private static final String PROMPT = "List the ten most popular programming languages";
    public static final String MODEL = "text-davinci-003";
    public static final int MAX_TOKENS = 1000;
    public static final double TEMPERATURE = 0.8;
    public static final boolean ECHO = true;

    @Test
    public void testGenerateCode() {
        OpenAiService service = new OpenAiService(TOKEN);
        CompletionRequest completionRequest = CompletionRequest.builder()
                .prompt(PROMPT)
                .model(MODEL)
                .maxTokens(MAX_TOKENS)
                .temperature(TEMPERATURE)
                .echo(ECHO)
                .build();

        service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
    }

}

That’s all there is to it.

You can find further information on different models on the main website.
https://platform.openai.com/docs/introduction/overview