Skip to content

Instantly share code, notes, and snippets.

@gantoin
Last active February 22, 2024 13:57
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • 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:

@dangkudo
Copy link

hello

@dangkudo
Copy link

what is your name?

@VJS-Tiger
Copy link

VJS-Tiger commented Feb 21, 2023

Thank you very much, the code from you helped me a lot in understanding the basics!
Just need to adjust a bit for my old bot with SDK (minSdkVersion 23)...

@JamesGoodsonDev
Copy link

this isnt chatgpt, this is contacting davinci 3......

@gantoin
Copy link
Author

gantoin commented Feb 27, 2023

this isnt chatgpt, this is contacting davinci 3......

Yes, this code is using davinci 3 model, ChatGPT is coming to OpenAI API soon. Here is the waiting list: https://share.hsforms.com/1u4goaXwDRKC9-x9IvKno0A4sk30

@bgreeson
Copy link

bgreeson commented Mar 5, 2023

Are you aware of any java tools that have been built to simplify API use?

@gantoin
Copy link
Author

gantoin commented Mar 6, 2023

Are you aware of any java tools that have been built to simplify API use?

No, I don't. But I planned to develop one with another mocking tool too.

@i-make-robots
Copy link

Thanks for this guide!

@SantiGameDev
Copy link

Thank you very much, the code from you helped me a lot in understanding the basics! Just need to adjust a bit for my old bot with SDK (minSdkVersion 23)...

Hold on, are you using this on a Rev Robotics Hub?

@nukuku123
Copy link

Hi, did anyone encounter this error while running the java code mentioned above? Not sure if it is network connection issue here.

Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:579)
at java.base/sun.nio.ch.Net.connect(Net.java:568)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:576)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:666)
at java.base/sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:304)
at java.base/sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:181)
at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:183)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:531)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:636)
at java.base/sun.net.www.protocol.https.HttpsClient.(HttpsClient.java:264)
at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:378)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:193)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1241)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1127)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:179)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1429)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1400)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:220)
at ChatGPT.chatGPT(ChatGPT.java:23)
at ChatGPT.main(ChatGPT.java:32)

@VJS-Tiger
Copy link

Thank you very much, the code from you helped me a lot in understanding the basics! Just need to adjust a bit for my old bot with SDK (minSdkVersion 23)...

Hold on, are you using this on a Rev Robotics Hub?

no, I have integrated ChatGPT along with other features into the Sanbot S1-B2 (Elf)...

@mohammad-ayan-008
Copy link

java.io.FileNotFoundException: https://api.openai.com/v1/completions
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:255)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:211)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:30)
at com.main.OpenAi.main(OpenAi.java:35)
at java.lang.reflect.Method.invoke(Native Method)
at com.duy.android.compiler.java.Java.run(Java.java:115)
at com.duy.ide.javaide.run.activities.ExecuteActivity.executeDex(ExecuteActivity.java:147)
at com.duy.ide.javaide.run.activities.ExecuteActivity.exec(ExecuteActivity.java:124)
at com.duy.ide.javaide.run.activities.ExecuteActivity.access$100(ExecuteActivity.java:45)
at com.duy.ide.javaide.run.activities.ExecuteActivity$1.run(ExecuteActivity.java:88)
at java.lang.Thread.run(Thread.java:919)
error while doing conn.getInpStream()

@W1813
Copy link

W1813 commented Jul 12, 2023

Hi, did anyone encounter this error while running the java code mentioned above? Not sure if it is network connection issue here.

Exception in thread "main" java.net.ConnectException: Connection timed out: connect at java.base/sun.nio.ch.Net.connect0(Native Method) at java.base/sun.nio.ch.Net.connect(Net.java:579) at java.base/sun.nio.ch.Net.connect(Net.java:568) at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:576) at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327) at java.base/java.net.Socket.connect(Socket.java:666) at java.base/sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:304) at java.base/sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:181) at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:183) at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:531) at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:636) at java.base/sun.net.www.protocol.https.HttpsClient.(HttpsClient.java:264) at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:378) at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:193) at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1241) at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1127) at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:179) at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1429) at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1400) at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:220) at ChatGPT.chatGPT(ChatGPT.java:23) at ChatGPT.main(ChatGPT.java:32)

I have encountered the same problem. How did you solve it?

@i-make-robots
Copy link

Connection timed out: connect

says it right there. probably service is too busy to answer all queries. same as when you get nothing and have to regenerate response.

@gantoin
Copy link
Author

gantoin commented Jul 19, 2023

OpenAI changed the token size limit, if you get a 400 please change to:

data.put("max_tokens", 2000);

@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