How to Use the ChatGPT API with Java

Samuel Catalano
The Fresh Writes
Published in
5 min readMar 22, 2023

As a large language model trained by OpenAI, ChatGPT provides an artificial intelligence service for natural language processing tasks. By using the ChatGPT API, developers can integrate the capabilities of the ChatGPT model into their applications. In this article, we will explore how to use the ChatGPT API with Java.

Step 1: Obtain an API Key

Before you can use the ChatGPT API, you will need to obtain an API key from OpenAI. You can do this by creating an account on the OpenAI website and following the instructions to create a new API key. The API key is a long string of letters and numbers that you will use to authenticate your API requests.

Step 2: Set Up Your Java Environment

To send API requests from Java, you will need to use a library that can make HTTP requests. We recommend using the OkHttp library, which is easy to use and widely supported.

To use OkHttp, you will need to add the following dependency to your Maven project:

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>

If you are not using Maven, you can download the OkHttp library from the official website and add it to your project manually.

Step 3: Send an API Request

Here’s an example of how to send an API request using OkHttp. To make an API request, you need to send a POST request to the ChatGPT API endpoint. The endpoint URL is https://api.openai.com/v1/engine/davinci-codex/completions.

Here’s an example of how to make an API request using OkHttp:

import okhttp3.*;

public class ChatGPTClient {
private static final String API_URL = "https://api.openai.com/v1/engines/davinci-codex/completions";

public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();

String prompt = "My name is";
String apiKey = "YOUR_API_KEY";

MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"prompt\": \"" + prompt + "\"}");

Request request = new Request.Builder()
.url(API_URL)
.post(body)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.build();

Response response = client.newCall(request).execute();
String responseBody = response.body().string();

System.out.println(responseBody);
}
}

This code sends a completion request to the ChatGPT API with the prompt “Hello, my name is” and prints the response body to the console. You can modify the prompt and other parameters as needed.

Step 4: Set the Request Body

The request body should contain a JSON object with the parameters for the completion request. The required parameter is the “prompt”, which specifies the input text to generate completions for. You can also set optional parameters such as “temperature”, “max_tokens”, and “top_p” to control the generation process.

Here’s an example of a completion request JSON object:

{
"prompt": "Hello, my name is",
"temperature": 0.5,
"max_tokens": 50,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
}

You can modify the prompt and other parameters as needed. The meaning of each parameter is as follows:

- "prompt": The input text to generate completions for.
- "temperature": Controls the randomness of the generated completions. Higher values result in more random completions.
- "max_tokens": The maximum number of tokens (words or punctuation marks) in each generated completion.
- "top_p": Controls the diversity of the generated completions. Lower values result in more diverse completions.
- "frequency_penalty": Penalizes completions that repeat words or phrases from the prompt.
- "presence_penalty": Penalizes completions that contain words or phrases not present in the prompt.

Step 5: Handle the API response

After sending the API request, you will receive a JSON object containing the generated completions. The response format is as follows:

{
"choices": [
{
"text": "My name is John.",
"index": 0,
"logprobs": null,
"finish_reason": "stop"
},
{
"text": "My name is Sarah.",
"index": 1,
"logprobs": null,
"finish_reason": "stop"
},
{
"text": "My name is David.",
"index": 2,
"logprobs": null,
"finish_reason": "stop"
}
]
}

The “choices” array contains one or more completions, each represented by a JSON object with the following fields:

"text": The generated completion text.
"index": The index of the completion in the list of generated completions.
"logprobs": The log probabilities of the tokens in the completion, used for debugging purposes.
"finish_reason": The reason why the completion generation stopped. Possible values are "stop", "max_tokens", "temperature", and "top_p".

You can parse the response JSON object using a JSON library such as Gson or Jackson. Here’s an example using Gson:

import com.google.gson.Gson;

public class ChatGPTClient {
// ...

public static void main(String[] args) throws Exception {
// ...

Gson gson = new Gson();
ChatGPTResponse response = gson.fromJson(responseBody, ChatGPTResponse.class);
for (ChatGPTCompletion completion : response.choices) {
System.out.println(completion.text);
}
}

private static class ChatGPTResponse {
private ChatGPTCompletion[] choices;
}

private static class ChatGPTCompletion {
private String text;
private int index;
private Object logprobs;
private String finish_reason;
}
}

This code uses Gson to parse the response JSON object into Java objects. The “ChatGPTResponse” class represents the top-level JSON object, and the “ChatGPTCompletion” class represents each completion object. The “text” field is printed to the console for each completion.

Conclusion

In this article, we have shown how to use the ChatGPT API with Java. By sending HTTP requests with the correct headers and body, and parsing the JSON response, you can integrate the power of the ChatGPT model into your Java applications.

Do support our publication by following it

--

--

Samuel Catalano
The Fresh Writes

Samuel is a Software Engineer from Brazil with main interests in Java, Spring Boot, Quarkus, Microservices, Docker, Databases, Kubernetes, and Clean Code