ChatGPT API in JAVA | (simple & easy)

Поделиться
HTML-код
  • Опубликовано: 22 мар 2023
  • 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 Description.
    ► ChatGPT API KEY:
    ● platform.openai.com/account/a...
    ► Software Used:
    ● IntelliJ IDEA: www.jetbrains.com/idea/download/
    ► Helpful Learning Sites:
    ● Codecademy: www.codecademy.com/
    ● freeCodeCamp: www.freecodecamp.org/
    ► Song Used:
    ● One More Time: • [FREE] Lofi Type Beat ...
    ► Support or Follow me:
    ● Join our Discord: / discord
    ● GitHub: github.com/SmallPlayz
    ● Twitter: / smallplayz_
    ● Instagram: / smallplayz_

Комментарии • 53

  • @mintype
    @mintype  Год назад +21

    (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  Год назад +1

      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 9 месяцев назад

      5head@@mintype

  • @mintype
    @mintype  9 месяцев назад +1

    join the discord! -> discord.gg/hhGu6mV5wm

  • @TheMrTuanVu
    @TheMrTuanVu Месяц назад +1

    thank you a lot for this video!

  • @TrendingView86
    @TrendingView86 Год назад

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

  • @mathsbigsecrets6100
    @mathsbigsecrets6100 8 месяцев назад +3

    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  8 месяцев назад +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)

  • @oroi196
    @oroi196 Год назад +2

    works for me. ty bro

  • @fathurrahmannursaputra4219
    @fathurrahmannursaputra4219 Месяц назад

    can you create for google gemini ?

  • @hosteldays3509
    @hosteldays3509 Месяц назад

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

  • @user-pu5bm7cj9w
    @user-pu5bm7cj9w 11 месяцев назад

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

    • @mintype
      @mintype  11 месяцев назад +2

      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 10 месяцев назад

      @@mintype hello

  • @debalinaghosh6404
    @debalinaghosh6404 9 месяцев назад

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

    • @mintype
      @mintype  9 месяцев назад

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

  • @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!

  • @silashartung4334
    @silashartung4334 Год назад +2

    This doesnt work for me

  • @adhimarnaek1924
    @adhimarnaek1924 Год назад

    what is String Model Used to

  • @PokeMichele
    @PokeMichele 11 месяцев назад

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

    • @mintype
      @mintype  11 месяцев назад +1

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

  • @giveaway5630
    @giveaway5630 3 месяца назад

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

    • @mintype
      @mintype  2 месяца назад

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

  • @hudashaikh5169
    @hudashaikh5169 7 месяцев назад +1

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

    • @mintype
      @mintype  7 месяцев назад

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

  • @ELLIOT-uq8nc
    @ELLIOT-uq8nc 9 месяцев назад +3

    YOU SHOULD MAKE MORE VIDEOS BRO

    • @mintype
      @mintype  9 месяцев назад

      On what

    • @ELLIOT-uq8nc
      @ELLIOT-uq8nc 9 месяцев назад +1

      on this topic ofc@@mintype

  • @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 3 месяца назад

      learn how to spell

  • @samshasti9519
    @samshasti9519 Год назад +3

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

    • @26manasviverma14
      @26manasviverma14 8 месяцев назад

      same bro please tell if you found any update/solutions

  • @meoconhoccode
    @meoconhoccode Месяц назад +1

    free account can't use api :(

  • @shashivadhangunti3411
    @shashivadhangunti3411 10 месяцев назад

    where is the code

    • @mintype
      @mintype  10 месяцев назад

      Its the pinned comment.

  • @user-tx6qd8fs1h
    @user-tx6qd8fs1h 4 месяца назад

    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  4 месяца назад

      Yeah you have to pay but its really cheap

  • @joseangelnavarro4116
    @joseangelnavarro4116 11 месяцев назад +3

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

    • @mintype
      @mintype  10 месяцев назад

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

    • @joseangelnavarro4116
      @joseangelnavarro4116 10 месяцев назад

      @@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 4 месяца назад

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

    • @ReeachyZ_
      @ReeachyZ_ 2 месяца назад

      ​@@mintypein first request this happens

    • @my__type4
      @my__type4 Месяц назад

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