Service Management Blog

How to Access ChatGPT’s API Using Java

TheTruthAboutContinuousDelivery
3 minute read
Nilesh Deshpande

ChatGPT is an artificial intelligence-based (AI) chatbot developed by OpenAI, built on top of the organization’s GPT-3.5 and GPT-4 large language models (LLM).

This blog post details how to write Java code to connect to OpenAI’s REST API. Once you start, you can add more functionality to your code.

Creating your account with OpenAI

  1. Create an account on https://platform.openai.com.
  2. Under Menu => Personal, select “View API keys.”
    OpenAIs-API-key-generation-screen

    Figure 1. OpenAI’s API key generation screen.

  3. Create and save your API key for later use.
  4. On the left-side Menu, select Organization =>Settings, and request that an “Organization ID” be generated. Copy this for later usage.
OpenAIs-setup-screen-to-create-an-Organization-ID

Figure 2. OpenAI’s setup screen to create an Organization ID.

Java code

You’ll need to create three files:

  1. FileHelper.java
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.LinkedList;
    import java.util.List;
    public class FileHelper {
    public static String readLinesAsString(File file) {
    List<String> returnLines = new LinkedList<String>();
    String text = "";
    try {
    text = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())),
    StandardCharsets.UTF_8);
    } catch (IOException e) {
    e.printStackTrace();
    }
    return text;
    }
    public static List<String> readLines(File file) {
    List<String> returnLines = new LinkedList<String>();
    try {
    String text = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())),
    StandardCharsets.UTF_8);
    String[] lines = text.split("\n");
    for (String line : lines) {
    returnLines.add(line);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    return returnLines;
    }
    public static void writeStringToFile(String line, File file) {
    try {
    FileWriter myWriter = null;
    if (file.exists()) {
    myWriter = new FileWriter(file, true);//if file exists append to file. Works fine.
    } else {
    System.out.println("Could not find the file " + file + ". Creating it again");
    file.createNewFile();
    myWriter = new FileWriter(file);
    }
    myWriter.write(line);
    myWriter.close();
    // System.out.println("Successfully wrote to the file. "+file.getAbsolutePath());
    } catch (IOException e) {
    e.printStackTrace();
    System.out.println("An error occurred in writing to file " + file + " e=" + e);
    }
    }
    }
  2. Request.json
    {
    "model": "text-davinci-003",
    "prompt": "Which was the best selling car 2021 in USA?",
    "max_tokens": 64,
    "temperature": 0.5
    }
  3. ChatGPTAPIExample.java
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    public class ChatGPTAPIExample {
    public static void listTokens() {
    try {
    //This API will fetch the models available.
    URL url = new URL("https://api.openai.com/v1/models");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Accept", "application/json");
    //Make sure you put the right Organization key saved earlier.
    con.setRequestProperty("OpenAI-Organization", "your-org-key");
    con.setDoOutput(true);
    //Make sure you put the right API Key saved earlier.
    con.setRequestProperty("Authorization", "Bearer your-api-key");
    int responseCode = con.getResponseCode();
    System.out.println("Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(
    new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
    }
    in.close();
    System.out.println(response);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    public static void prompts() {
    try {
    URL url = new URL("https://api.openai.com/v1/completions");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Accept", "application/json");
    //Make sure you put the right Organization key saved earlier.
    con.setRequestProperty("OpenAI-Organization", "your-org-key");
    con.setDoOutput(true);
    //Make sure you put the right API Key saved earlier.
    con.setRequestProperty("Authorization", "Bearer your-api-key");
    //Make sure to relace the path of the json file created earlier.
    String jsonInputString = FileHelper.readLinesAsString(new File("C:\\yourpath\\request.json"));
    try (OutputStream os = con.getOutputStream()) {
    byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
    os.write(input, 0, input.length);
    }
    int responseCode = con.getResponseCode();
    System.out.println("Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(
    new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
    }
    in.close();
    System.out.println(response);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    public static void main(String[] args) {
    listTokens();
    prompts();
    }
    }

Compile and run them once you have the files created. You can build and run in a way that’s most comfortable for you. For example, even using the command line should work, as follows:

javac *.java
java ChatGPTAPIExample

Sample output
Response Code : 200

{“id”:”cmpl-6wFzNtira0jiFrmXHOUkjZpqytNca”,”object”:”text_completion”,”created”:1679342505,”model”:”text-davinci-003″,”choices”:[{“text”:”\n\nIt is too early to tell which car will be the best-selling car in 2022 in the USA.”,”index”:0,”logprobs”:null,”finish_reason”:”stop”}],”usage”:{“prompt_tokens”:10,”completion_tokens”:22,”total_tokens”:32}}

Conclusion

Now that you’ve learned how to get started connecting an application to OpenAI’s API and can integrate it with other applications, you can take advantage of more of ChatGPT’s capabilities. For more details, please refer to https://platform.openai.com/docs/api-reference.

 

Try BMC’s AIOps Capabilities - Free!

Start your free, easy-to-use, self-service trial to see firsthand how BMC Helix Operations Management with AIOps can revolutionize the way your enterprise does IT.


These postings are my own and do not necessarily represent BMC's position, strategies, or opinion.

See an error or have a suggestion? Please let us know by emailing blogs@bmc.com.

Business, Faster than Humanly Possible

BMC empowers 86% of the Forbes Global 50 to accelerate business value faster than humanly possible. Our industry-leading portfolio unlocks human and machine potential to drive business growth, innovation, and sustainable success. BMC does this in a simple and optimized way by connecting people, systems, and data that power the world’s largest organizations so they can seize a competitive advantage.
Learn more about BMC ›

About the author

Nilesh Deshpande

Nilesh specializes in working with Enterprise Customers, debugging complex performance-related issues, and providing tuning recommendations