Creating a custom AI Chatbot in Java and OpenAI

This post describes how to build a basic AI chatbot in Java, leveraging the OpenAI API. Before beginning, make sure that you have Eclipse, Java, and Maven installed (see this post for instructions).

Create an API Key on OpenAI

An API key needs to be created on OpenAI. You must have and account created on the site. If you do not have an account, then sign up for free.

This API key will be referenced in your code and authorizes your code to make a call to the OpenAI API.

  1. Navigate to OpenAI.
  2. Click on API login and login.
  3. Click on API.
  1. You will be presented with a dashboard; click on API keys.
  2. Click on Create new secret key.
  3. Give it a name (e.g., "AI ChatBot Key") and you can keep it in the Default project, then click on Create secret key.
  4. Note the key down (e.g., smk3q...rnynf9YeKltt) as it will be used in your code.

Create a Maven project in Eclipse

Our Java code will be developed in Eclipse.

  1. In Eclipse, click on File > New > Maven Project.
  2. Select "Create a simple project (skip archetype selection)" then click Next.
  1. Add a group id (e.g., chatbot), artifact id (e.g., chatbot), and description (e.g., MyFirstChatbot) then click Finish.
  1. Expand openai and double-click on pom.xml to edit the file.
  1. Enter the following content into the pom.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.cgpt</groupId>
  <artifactId>ChatGPTJavaApplication</artifactId>
  <version>1.0-SNAPSHOT</version>

</project>
  1. Right-click on src/main/java and select New > Class.
  2. For Name, enter "MyChatbot" then click "Finish".
  3. Add this code to the newly created MyChatbot.java file.
package openai;

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

public class MyChatbot {

  // This method is called every time the user enters some input
  public static String chatGPT(String myprompt) {

    // Static values
    String url = "https://api.openai.com/v1/chat/completions";
    String apiKey = "XXXXXXXXXXXXXX"; // this is the OpenAI API key
    String model = "gpt-4o";
    String myrole = "system"; // can be set to 'user'; system allows you to specify the way the model answers questions
    String maxTokens = "500";
    String temperature = "0.3"; // from 0-2, lower temperatures produce more predictable and consistent outputs

    // Training data or knowledge base
    String mycontent = "Your name is Ahmed and you are an AI clone of the real Ahmed Aboulnaga."
        + "When responding, be more informal than formal."
        + "You are writing a book titled 'DevSecOps on Oracle Cloud' which is set to be published in 2025."
        + "The chapters you have written are on Terraform, DevOps, networking, and storage."
        + "When asked about the content of the data, mimic someone with a personality that is honest, but can be sarcastic at times."
        + "In the responses, keep the answers brief but engaging."
        + "Some of your favorite hobbies are watching movies, reading comic books, and playing basketball."
        + "One of your favorite comic book series is called 'Rising Stars'.";

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

      // Submit the values above, including the training data, and the user input
      String body = "{\"max_tokens\": " + maxTokens + ", \"temperature\": " + temperature + ", \"model\": \""
          + model + "\", \"messages\": [{\"role\": \"" + myrole + "\", \"content\": \"" + mycontent + " "
          + myprompt + "\"}]}";
      connection.setDoOutput(true);
      OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
      writer.write(body);
      writer.flush();
      writer.close();

      // Receive 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 from the JSON response
      return extractMessageFromJSONResponse(response.toString());

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

  // This method simply extracts the response from the large JSON response
  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) {
    try {
      Scanner scanner = new Scanner(System.in);
      System.out.println("\nAI CHATBOT: Hi I am chatGPT. Ask me something! Type 'bye' to exit.\n");
      Boolean exit = false;

      // This loop will continue the chat until the user enters 'bye'
      while (!exit) {
        String myinput = scanner.nextLine();
        if ("bye".equals(myinput.toLowerCase())) {
          System.out.println("Bye!");
          exit = true;
          break;
        }
        System.out.println("AI CHATBOT: " + chatGPT(myinput) + "\n");
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

Execute the Code

Now that the code is developed, it can be executed directly from Eclipse.

  1. Right-click on "MyChatbot.java" and click on "Run As" then click on "Java Application".

You will notice that some of the responses from the AI chatbot are from the knowledge base provided while others have been pulled from OpenAI's scrapping of sources on the Internet. Be mindful of hallucinations!

References