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.


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


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;

    public void testGenerateCode() {
        OpenAiService service = new OpenAiService(TOKEN);
        CompletionRequest completionRequest = CompletionRequest.builder()



That’s all there is to it.

You can find further information on different models on the main website.