Blog |

How to Use the ChatGPT API with Java

How to Use the ChatGPT API with Java
Table of Contents

Imagine harnessing the power of ChatGPT's human-like responses right from your Java code! It'd be like adding a supercharger to your already powerful engine.

This step-by-step, hands-on guide (with full example code at the end) will show you exactly how to integrate, interact, and leverage this union so you can build smarter applications. Before you know it, you'll have Java and ChatGPT playing nice to deliver a user experience that's nothing short of mind-blowing.

Step 1: Set up the development environment

  1. Install the Java Development Kit (JDK) if not already installed.
  2. Set up a Java project using your favorite IDE or command-line tools.

Step 2: Sign up for the OpenAI API

Go to https://beta.openai.com/signup/ and sign up to get an API key that you will use to authenticate your requests.

Sign up for OpenAI API key
Sign up for OpenAI API

Step 3: Write Java code to connect to the OpenAI API

  1. Import necessary Java classes: Import the required classes for handling HTTP connections and I/O operations.
  2. Create a class named ChatGPTAPIExample: The main class where the integration code is written.
  3. Define the ChatGPT method: The method takes the user prompt as input and returns the response from ChatGPT. It sends the request to the ChatGPT API endpoint and then extracts the response.
  4. Define the necessary parameters:
    • URL: The URL for the ChatGPT API endpoint.
    • OpenAI API key: The OpenAI API key which is obtained in step 2.
    • Model: The ChatGPT model that will be used. For example, gpt-3.5-turbo .
  5. Create an HTTP POST request: Create an object with the API endpoint URL.
  6. Open a HTTP connection to the created URL object. Create the POST request method with the necessary request headers.
  7. Create the request body: Create a JSON string request body with the model and the user prompt.
  8. Send the request and retrieve the response: Send the request and read the response and store it in a buffer.
  9. Process the response: Extract the response which is in the JSON format and extract the message actually needed.
  10. Handle exceptions: Handle the IOException which might occur during the API request.
  11. Define the main method: This is an entry point of your program where you can test the code and call the chatGPT method with a sample prompt and see the response.

Example: ChatGPT integration with Java code

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class ChatGPTAPIExample {

   public static String chatGPT(String prompt) {
       String url = "https://api.openai.com/v1/chat/completions";
       String apiKey = "YOUR API KEY HERE";
       String model = "gpt-3.5-turbo";

       try {
           URL obj = new URL(url);
           HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
           connection.setRequestMethod("POST");
           connection.setRequestProperty("Authorization", "Bearer " + apiKey);
           connection.setRequestProperty("Content-Type", "application/json");

           // The request body
           String body = "{\"model\": \"" + model + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + prompt + "\"}]}";
           connection.setDoOutput(true);
           OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
           writer.write(body);
           writer.flush();
           writer.close();

           // Response from ChatGPT
           BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
           String line;

           StringBuffer response = new StringBuffer();

           while ((line = br.readLine()) != null) {
               response.append(line);
           }
           br.close();

           // calls the method to extract the message.
           return extractMessageFromJSONResponse(response.toString());

       } catch (IOException e) {
           throw new RuntimeException(e);
       }
   }

   public static String extractMessageFromJSONResponse(String response) {
       int start = response.indexOf("content")+ 11;

       int end = response.indexOf("\"", start);

       return response.substring(start, end);

   }

   public static void main(String[] args) {

       System.out.println(chatGPT("hello, how are you? Can you tell me what's a Fibonacci Number?"));

   }
}

Output: ChatGPT integration with Java code example

Hello! I'am an AI, so I don't have feelings, but I'm here to help you. A Fibonacci number refers to a number in the Fibonacci sequence. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. So, for example, the first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, and so on.

Process finished with exit code 0

Congrats! You’ve integrated ChatGPT with Java using the OpenAI API.

It’s important to note that although ChatGPT is magical, it does not have human-level intelligence. Responses shown to your users should always be properly vetted and tested before being used in a production context. Don’t expect ChatGPT to understand the physical world, use logic, be good at math, or check facts.

Note: At times when trying to connect to ChatGPT’s API you might encounter 429 error Too Many Requests . This occurs when the rate limits set by OpenAI are exceeded. To overcome this either create a new account in OpenAI and then use that API key or upgrade to a paid plan that has extended rate limits.

How to handle errors from the ChatGPT API

It's a best practice to monitor exceptions that occur when interacting with any external API. For example, the API might be temporarily unavailable, or the expected parameters or response format may have changed and you might need to update your code, and your code should be the thing to tell you about this. Here's how to do it with the error monitoring platform Rollbar:

Step 1: Set up your account on Rollbar and obtain the Rollbar access token.

Step 2: Add the Rollbar Java SDK dependency to your Java project and to the build configuration file (for example, the Maven pom.xml or the Gradle build.gradle). Here is an illustration for Maven:

<dependency>
    <groupId>com.rollbar</groupId>
    <artifactId>rollbar-java</artifactId>
    <version>1.10.0</version>
</dependency>

Step 3: Next, setup the Rollbar configuration with your Java code that is interacting with the ChatGPT API.

import com.rollbar.notifier.Rollbar;
import com.rollbar.notifier.config.Config;
import com.rollbar.notifier.config.ConfigBuilder;

public class ChatGPTExample {

    public static void main(String[] args) {
        // Configure Rollbar
      Config rollbarConfig =
      ConfigBuilder.withAccessToken("YOUR_ROLLBAR_ACCESS_TOKEN")
                .environment("production")
                .build();
      Rollbar rollbar = new Rollbar(rollbarConfig);

        try {
            // Code for interacting with the ChatGPT API
        } catch (Exception e) {
            rollbar.error(e);
        } finally {
            rollbar.close();
        }
    }
}

Make sure you replace the YOUR_ROLLBAR_ACCESS_TOKEN with your access token obtained from Rollbar.

To get your Rollbar access token, sign up for free and follow the instructions for Java.

We can't wait to see what you build with ChatGPT. Happy coding!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape