Skip to content

Instantly share code, notes, and snippets.

@gantoin
Last active May 1, 2024 22:18
Show Gist options
  • Save gantoin/190684c344bb70e5c5f9f2339c7be6ed to your computer and use it in GitHub Desktop.
Save gantoin/190684c344bb70e5c5f9f2339c7be6ed to your computer and use it in GitHub Desktop.
🤖 How to use ChatGPT API in your Java application?

🤖 How to use ChatGPT API in your Java application?

tags: chatgpt, java, api

Hi guys 👋 I'm sure you enjoy using chat GPT to produce, optimise, or translate code from any programming language to Java.

Today I'll show you how to use OpenAI ChatGPT API with Java, it's pretty easy.

1. Register for an API key

First, you'll need to register for an API key by going to the OpenAI API page. Follow the instructions to create an account and obtain an API key.

2. Enter a credit card into your OpenAI account

OpenAI blocks the API calls for exceeded your current quota when you don't have any card registered in your account. So, you will need to configure one.

3. Implements code like:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class ChatGPT {
    public static void chatGPT(String text) throws Exception {
        String url = "https://api.openai.com/v1/completions";
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer YOUR-API-KEY");

        JSONObject data = new JSONObject();
        data.put("model", "text-davinci-003");
        data.put("prompt", text);
        data.put("max_tokens", 4000);
        data.put("temperature", 1.0);

        con.setDoOutput(true);
        con.getOutputStream().write(data.toString().getBytes());

        String output = new BufferedReader(new InputStreamReader(con.getInputStream())).lines()
                .reduce((a, b) -> a + b).get();

        System.out.println(new JSONObject(output).getJSONArray("choices").getJSONObject(0).getString("text"));
    }

    public static void main(String[] args) throws Exception {
        chatGPT("Hello, how are you?");
    }
}

It works!

src.main.java.ChatGPT


I'm doing great, thank you for asking. How about you?

Process finished with exit code 0

Resources used:

@Pocanistaken
Copy link

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 429 for URL: https://api.openai.com/v1/completions
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1902)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1500)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:268)
at skript.chatgpt.SkriptChatGPT.chatGPT(SkriptChatGPT.java:34)
at skript.chatgpt.SkriptChatGPT.main(SkriptChatGPT.java:42)
C:\Users\ali\AppData\Local\NetBeans\Cache\14\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\ali\AppData\Local\NetBeans\Cache\14\executor-snippets\run.xml:94: Java returned: 1
BUILD FAILED (total time: 0 seconds)

@Pocanistaken
Copy link

Do you know why I'm getting rate limited i didn't even use the api maybe my network ip address is blocked? (using Hetzner)

@MomoTheDev
Copy link

Don't construct the URL object using the constructor new URL(String), that's deprecated and would throw exceptions like "FileNotFoundException", "IOException" and so on. Please use this instead:

final URL url = new URI("URL_HERE").toURL();

This would fix the issues encountered by @mohammad-ayan-008 and @W1813

@NguyenTanDung-2004
Copy link

I dont know why
"Exception in thread "main" java.io.IOException: Server returned HTTP response code: 429 for URL: https://api.openai.com/v1/completions
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1997)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1589)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224)
at testMaven.ChatGPT.chatGPT(ChatGPT.java:27)
at testMaven.ChatGPT.main(ChatGPT.java:34)
"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment