ChatGPT API in JAVA | (simple & easy)

แชร์
ฝัง
  • เผยแพร่เมื่อ 9 ก.พ. 2025
  • ChatGPT API in JAVA | (simple & easy)
    In today's video, I will be showing you how to use ChatGPT's API in Java.
    ► Code Used:
    ● Check the pinned comment.
    ► ChatGPT API KEY:
    ● platform.opena...
    ► Software Used:
    ● IntelliJ IDEA: www.jetbrains....
    ► Helpful Learning Sites:
    ● Codecademy: www.codecademy...
    ● freeCodeCamp: www.freecodeca...
    ► Song Used:
    ● One More Time: • [FREE] Lofi Type Beat ...
    ► Support or Follow me:
    ● Join our Discord: / discord
    ● GitHub: github.com/Min...

ความคิดเห็น • 72

  • @mintype
    @mintype  ปีที่แล้ว +33

    (updated june 2023)
    API KEY: no longer works! get your own! link in desc!
    Code Used:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    public class Main {
    public static void main(String[] args) {
    System.out.println(chatGPT("hello, how are you?"));
    // Prints out a response to the question.
    }
    public static String chatGPT(String message) {
    String url = "api.openai.com/v1/chat/completions";
    String apiKey = "KEY GOES HERE!!!!!!!!!!!"; // API key goes here
    String model = "gpt-3.5-turbo"; // current model of chatgpt api
    try {
    // Create the HTTP POST request
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", "Bearer " + apiKey);
    con.setRequestProperty("Content-Type", "application/json");
    // Build the request body
    String body = "{\"model\": \"" + model + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + message + "\"}]}";
    con.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
    writer.write(body);
    writer.flush();
    writer.close();
    // Get the response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
    }
    in.close();
    // returns the extracted contents of the response.
    return extractContentFromResponse(response.toString());
    } catch (IOException e) {
    throw new RuntimeException(e);
    }
    }
    // This method extracts the response expected from chatgpt and returns it.
    public static String extractContentFromResponse(String response) {
    int startMarker = response.indexOf("content")+11; // Marker for where the content starts.
    int endMarker = response.indexOf("\"", startMarker); // Marker for where the content ends.
    return response.substring(startMarker, endMarker); // Returns the substring containing only the response.
    }
    }

    • @urboigot45iron4
      @urboigot45iron4 ปีที่แล้ว

      nice

    • @nadavel85
      @nadavel85 ปีที่แล้ว +1

      Ran the above code in InteliJ and got ssl handshake exception. Any ideas on how to get this to work?

    • @mintype
      @mintype  ปีที่แล้ว +2

      1. Try running code locally on your computer if you aren't already.
      2. make sure you are connected to wifi or ethernet (obv)
      3. make sure ur code is the same as mine exactly!
      4. make sure you use your own api-key!
      if you still are having trouble, maybe ask chatgpt how to fix itself lol

    • @nadavel85
      @nadavel85 ปีที่แล้ว +1

      @@mintype I got it to work, just needed to download the ssl certificate from the api url and to add it to the project in InteliJ, Thanks

    • @mre3xaz
      @mre3xaz ปีที่แล้ว

      5head@@mintype

  • @mintype
    @mintype  ปีที่แล้ว +1

    join the discord! -> discord.gg/hhGu6mV5wm

  • @mathsbigsecrets6100
    @mathsbigsecrets6100 ปีที่แล้ว +4

    I get an "Server returned HTTP response code: 429" Error. I believer the BufferedReader in is what's causing the issue. Any ideas on what might be going wrong?

    • @mintype
      @mintype  ปีที่แล้ว +1

      Check your api key is valid not expired and works. Also check how much free trial money you have left if you are in the free trial. (Other people have had the same issue before)

    • @RichaBehera129
      @RichaBehera129 5 หลายเดือนก่อน

      ​@@mintype Even I am getting the same error any idea I doing a poc for a very important project can anyone help me please .

  • @TheMrTuanVu
    @TheMrTuanVu 9 หลายเดือนก่อน +2

    thank you a lot for this video!

  • @oroi196
    @oroi196 ปีที่แล้ว +2

    works for me. ty bro

  • @ELLIOT-uq8nc
    @ELLIOT-uq8nc ปีที่แล้ว +5

    YOU SHOULD MAKE MORE VIDEOS BRO

    • @mintype
      @mintype  ปีที่แล้ว

      On what

    • @ELLIOT-uq8nc
      @ELLIOT-uq8nc ปีที่แล้ว +1

      on this topic ofc@@mintype

  • @XiaoleGuo
    @XiaoleGuo ปีที่แล้ว +1

    Hey, how could I get the Java codes? You mentioned that check description, but I failed to find it...

    • @mintype
      @mintype  ปีที่แล้ว +3

      Heres the code (updated):
      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
      import java.io.OutputStreamWriter;
      import java.net.HttpURLConnection;
      import java.net.URL;
      public class Main {
      public static void main(String[] args) {
      System.out.println(chatGPT("hello, how are you?"));
      // Prints out a response to the question.
      }
      public static String chatGPT(String message) {
      String url = "api.openai.com/v1/chat/completions";
      String apiKey = "KEY GOES HERE!!!!!!!!!!!"; // API key goes here
      String model = "gpt-3.5-turbo"; // current model of chatgpt api
      try {
      // Create the HTTP POST request
      URL obj = new URL(url);
      HttpURLConnection con = (HttpURLConnection) obj.openConnection();
      con.setRequestMethod("POST");
      con.setRequestProperty("Authorization", "Bearer " + apiKey);
      con.setRequestProperty("Content-Type", "application/json");
      // Build the request body
      String body = "{\"model\": \"" + model + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + message + "\"}]}";
      con.setDoOutput(true);
      OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
      writer.write(body);
      writer.flush();
      writer.close();
      // Get the response
      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuffer response = new StringBuffer();
      while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
      }
      in.close();
      // returns the extracted contents of the response.
      return extractContentFromResponse(response.toString());
      } catch (IOException e) {
      throw new RuntimeException(e);
      }
      }
      // This method extracts the response expected from chatgpt and returns it.
      public static String extractContentFromResponse(String response) {
      int startMarker = response.indexOf("content")+11; // Marker for where the content starts.
      int endMarker = response.indexOf("\"", startMarker); // Marker for where the content ends.
      return response.substring(startMarker, endMarker); // Returns the substring containing only the response.
      }
      }

    • @supercodingandmath2826
      @supercodingandmath2826 ปีที่แล้ว

      @@mintype hello

    • @Hakan_2033
      @Hakan_2033 3 หลายเดือนก่อน

      @@supercodingandmath2826 can you share github repo address?

  • @TrendingView86
    @TrendingView86 ปีที่แล้ว

    bro i have getting 3 errors near regex: beginIndex: it's saying : is not corroct in vs code

  • @BrennerEraFan
    @BrennerEraFan 6 หลายเดือนก่อน

    Could you please make a video explaining how to use Ollama API with java?
    Ollama is a command-line based program that runs locally and runs models like llama2, llama3, etc...

    • @mintype
      @mintype  6 หลายเดือนก่อน

      ill see about that!

    • @BrennerEraFan
      @BrennerEraFan 6 หลายเดือนก่อน

      @@mintype Thank you so much!

    • @mintype
      @mintype  6 หลายเดือนก่อน +1

      I've just finished recording the video! So expect it to be released soon!

    • @BrennerEraFan
      @BrennerEraFan 6 หลายเดือนก่อน

      @@mintype OMG thank you so much!!

    • @mintype
      @mintype  6 หลายเดือนก่อน +1

      im done editing and working on thumbnail now :)

  • @silashartung4334
    @silashartung4334 ปีที่แล้ว +2

    This doesnt work for me

  • @fathurrahmannursaputra4219
    @fathurrahmannursaputra4219 9 หลายเดือนก่อน

    can you create for google gemini ?

  • @debalinaghosh6404
    @debalinaghosh6404 ปีที่แล้ว

    when I ask for a java program it is not giving the complete output. Could you help me in this?

    • @mintype
      @mintype  ปีที่แล้ว

      Prompt the API with "continue" after if it is incomplete.

  • @hosteldays3509
    @hosteldays3509 9 หลายเดือนก่อน

    Yes I use my api key but it why the link cgatgpt link is not working

  • @sty1623
    @sty1623 2 หลายเดือนก่อน

    How do I fix error code 429? noone else has my api key

    • @mintype
      @mintype  2 หลายเดือนก่อน

      Either you have reached the rate limit OR you don't have enough funds in your OpenAI account.

    • @sty1623
      @sty1623 2 หลายเดือนก่อน

      @@mintype i have never used any api key and i have enough funds in my account

  • @Spider-Man_67
    @Spider-Man_67 ปีที่แล้ว

    Ca we do the same thing in VS COde?

    • @mintype
      @mintype  ปีที่แล้ว

      Yes, it will work in VS Code, just make sure to use all the right imports!

  • @adhimarnaek1924
    @adhimarnaek1924 ปีที่แล้ว

    what is String Model Used to

    • @mintype
      @mintype  ปีที่แล้ว

      gpt-3.5-turbo

  • @PokeMichele
    @PokeMichele ปีที่แล้ว

    I don't know why it always refuses the connection when i try to execute it

    • @mintype
      @mintype  ปีที่แล้ว +1

      Check if your API free trial has expired yet. Many people get the same issue and don't realize their trial has expired.

  • @Hakan_2033
    @Hakan_2033 3 หลายเดือนก่อน

    can you share github repo address?

    • @mintype
      @mintype  2 หลายเดือนก่อน

      Theres no repo for this but there is code in the pinned comment

  • @TrendingView86
    @TrendingView86 ปีที่แล้ว +4

    hello bro can u plz make more video's like this only diffrent i love this type of consept's

    • @Solrac924
      @Solrac924 ปีที่แล้ว

      learn how to spell

  • @huynhthanhliem11x13
    @huynhthanhliem11x13 9 หลายเดือนก่อน +1

    free account can't use api :(

  • @giveaway5630
    @giveaway5630 11 หลายเดือนก่อน

    Requires GPT-4, because when reading an error message after asking, getting insufficient credits

    • @mintype
      @mintype  10 หลายเดือนก่อน

      It means your openAI account doesn’t have any funds/money left

  • @samshasti9519
    @samshasti9519 ปีที่แล้ว +3

    This doesn't work for me. Did open ai change anything?

    • @26manasviverma14
      @26manasviverma14 ปีที่แล้ว

      same bro please tell if you found any update/solutions

  • @hudashaikh5169
    @hudashaikh5169 ปีที่แล้ว +1

    i got server 429 error for first time why is it happening

    • @mintype
      @mintype  ปีที่แล้ว

      Check your api key is working and valid. Make sure it is not expired if it is a free trial.

  • @shashivadhangunti3411
    @shashivadhangunti3411 ปีที่แล้ว

    where is the code

    • @mintype
      @mintype  ปีที่แล้ว

      Its the pinned comment.

  • @joseangelnavarro4116
    @joseangelnavarro4116 ปีที่แล้ว +3

    I can't get the code to work. Error 429. I have created another user with another key

    • @mintype
      @mintype  ปีที่แล้ว

      Error 429 may happen to you if you send too many requests in a short period of time.

    • @joseangelnavarro4116
      @joseangelnavarro4116 ปีที่แล้ว

      @@mintype with a new user and new key if i do the first request the code is it. Is possible any change with free counter politic?

    • @ece03abhisheksrivastava64
      @ece03abhisheksrivastava64 ปีที่แล้ว

      @@mintype Bro even showing 429 for first time call 🤔

    • @ReeachyZ_
      @ReeachyZ_ 10 หลายเดือนก่อน

      ​@@mintypein first request this happens

    • @my__type4
      @my__type4 9 หลายเดือนก่อน

      Does anyone solve this problem? I'm having the same issue. I'm using Eclipse IDE

  • @LynnLunnHtun
    @LynnLunnHtun ปีที่แล้ว

    I think API keys are expired now, so we must pay to run the code?
    Plz. reply me as fast as you can, i must finish my project in next two weeks

    • @mintype
      @mintype  ปีที่แล้ว

      Yeah you have to pay but its really cheap