Java program access ChatGPT

0 Preface

In the previous article, we talked about how to register and use the recently popular ChatGPT? In this issue, let's take a look at how to call the ChatGPT interface in Java.
Portal spent 1 yuan to experience a recently popular ChatGPT
insert image description here

Later, another big guy connected ChatGPT to WeChat and came out as a WeChat robot to provide us with services.
The new method of Portal ChatGPT is here, the WeChat chat robot
insert image description here
, but due to various reasons, the robot on WeChat is temporarily unusable (it’s not her aloofness...), as for whether it can be restored later, I don’t know.
insert image description here

insert image description here

1 Friends who still want to experience can try

For various reasons, there are still many small partners who encountered various pitfalls like me and failed to experience ChatGPT.

  • no scientific internet tools
  • I can’t register my mobile phone number.
    insert image description here
    insert image description here
    Just yesterday, I received a notice from the official account of CSDN Yuanruyi, which probably means that [Ape Ruyi] has launched the GhatGPT function and invites you to evaluate it. You can also experience ChatGPT here.
    insert image description here
    The official address is here: Ape Ruyi download address
    Support Mac, Windows, Linux platforms to download
    insert image description here
    After the installation is complete, you can experience it
    insert image description here
    insert image description here

Anyway, Chat GPT still brings us a lot of surprises, especially for us programmers, it is a good assistant. Next, let's talk about how to use Java programs to access Chat GPT

2 Preparations before Java access

We need to obtain API keys at the following URL . Those who have registered for a ChatGPT account before can log in directly with the previous account. If there is no need to apply for an account
https://beta.openai.com/account/api-keys
insert image description here
click above After the screenshot button, the official will help us create a key . This key is very important and should be kept by yourself. It will be used in subsequent interface calls
insert image description here

3 Officially supported access languages

We log in to the following website, we can see that ChatGPT already supports many languages ​​to access
https://beta.openai.com/docs/libraries/community-libraries

insert image description here
Click the link above, you can jump to a GitHub address openai-java , Theo Kanning developer has written an example for us, we can refer to his open source project call
insert image description here

4 call fee

When the program is connected to chatGPT , the interface called will be charged .
However, the newly registered account is free for the first 3 months, and the total consumption amount does not exceed 18 US dollars .
My account is until April 1, 2023. During this period, as long as the call fee does not exceed 18 US dollars, it is equivalent to free use
insert image description here

5 Interface Call Description

After the above preparations are done, we can start to access ChatGPT. The following is a call example
given by the official website (just one of the usage scenarios), we should be familiar with these parameters

curl https://api.openai.com/v1/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    
    
  "model": "text-davinci-003",
  "prompt": "I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: What is human life expectancy in the United States?\nA: Human life expectancy in the United States is 78 years.\n\nQ: Who was president of the United States in 1955?\nA: Dwight D. Eisenhower was president of the United States in 1955.\n\nQ: Which party did he belong to?\nA: He belonged to the Republican Party.\n\nQ: What is the square root of banana?\nA: Unknown\n\nQ: How does a telescope work?\nA: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n\nQ: Where were the 1992 Olympics held?\nA: The 1992 Olympics were held in Barcelona, Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\nQ: Where is the Valley of Kings?\nA:",
  "temperature": 0,
  "max_tokens": 100,
  "top_p": 1,
  "frequency_penalty": 0.0,
  "presence_penalty": 0.0,
  "stop": ["\n"]
}'

We will not expand here, just talk about a few of the more important ones

  • model access model
    OpenAI API provides a series of models with different functions and price points, which can be viewed at the following address
    https://beta.openai.com/docs/models
    insert image description here
    Among them, GPT-3 is the most intelligent model and also the most expensive Yes, we will use text-davinci-003 in the following code
    insert image description here
  • Usage Scenarios
    The official website lists many usage scenarios for us, which can be viewed at
    https://beta.openai.com/examples
    ①Answers (question-and-answer scenario)
    insert image description here
    ②Classification (classification scenario)
    insert image description here
    ③Code (code scenario)
    insert image description here
    ④ Conversation (conversation scenario)
    insert image description here
    ⑤Translation ( translation scene)
    insert image description here

⑥Transformation (conversion scene)
insert image description here

6 code implementation

There are many scenes mentioned above, counting them, there are 49 scenes. In the code, we will select several of the scenarios to implement the following, and
interested friends in other scenarios will implement it by themselves.
We have taken the Q&A scene as an example, as long as you click the scene icon, you can jump to the scene call instance. details as follows

insert image description here
insert image description here

6.1 postman call

Let's use the postman tool to call it first to see if it can be adjusted.

If you don’t have the postman tool, you can download it from the address below, and I will prepare it for you

Link: https://pan.baidu.com/s/1ASJgyMRAw7RFmteiPXmzSA
Extraction code: v3ca

①Choose the request method, access address, and add the Token created by your own account
insert image description here
②Add the Content-Type type to json in the request header
insert image description here
③Join the input parameters in json format
insert image description here
④The call is successful and the result we want is returned
insert image description here

6.2 Java calls

The call in the postman tool is successful, so how to implement it in the code?
① We use idea to create a maven project
insert image description here
② Add dependencies

The dependency only needs to import Hutool, we use Hutool tool to send http post request, json object encapsulation and so on.

Hutool official address: https://hutool.cn/docs/

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.10</version>
</dependency>

③Java code
**Note: **In the code posted below, .bearerAuth("填写自己注册的token")you need to replace it with the Token key you created

import cn.hutool.http.*;
import cn.hutool.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class ChatGptDemo {
    
    
    public static void main(String[] args) {
    
    
        Map<String,String> headers = new HashMap<String,String>();
        headers.put("Content-Type","application/json;charset=UTF-8");

        JSONObject json = new JSONObject();
        //选择模型
        json.set("model","text-davinci-003");
        //添加我们需要输入的内容
        json.set("prompt","Oracle 计算年龄,精确到天,格式为xx岁xx月xx天?");
        json.set("temperature",0.9);
        json.set("max_tokens",2048);
        json.set("top_p",1);
        json.set("frequency_penalty",0.0);
        json.set("presence_penalty",0.6);

        HttpResponse response = HttpRequest.post("https://api.openai.com/v1/completions")
                .headerMap(headers, false)
                .bearerAuth("填写自己注册的token")
                .body(String.valueOf(json))
                .timeout(5 * 60 * 1000)
                .execute();

        System.out.println(response.body());
    }
}

//The call result returns
the text node under the choices node, which is the result we want

{
    
    
    "id": "cmpl-6ONatHFX9tCGfcxgMP6obP6lN1ROf",
    "object": "text_completion",
    "created": 1671268587,
    "model": "text-davinci-003",
    "choices": [
        {
    
    
            "text": "\n\nselect trunc(months_between(sysdate, date_of_birth)/12) 岁,\n       trunc(mod(months_between(sysdate, date_of_birth), 12)) 月,\n       trunc(sysdate-add_months(date_of_birth, trunc(months_between(sysdate, date_of_birth)))) 天\nfrom   table_name;",
            "index": 0,
            "logprobs": null,
            "finish_reason": "stop"
        }
    ],
    "usage": {
    
    
        "prompt_tokens": 43,
        "completion_tokens": 89,
        "total_tokens": 132
    }
}

Let's have fun, let it help us generate two pictures of beautiful girls

import cn.hutool.http.*;
import cn.hutool.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class ChatGptDemo001 {
    
    
    public static void main(String[] args) {
    
    
        Map<String,String> headers = new HashMap<String,String>();
        headers.put("Content-Type","application/json;charset=UTF-8");

        JSONObject json = new JSONObject();
        //搜索关键字
        json.set("prompt","漂亮小姐姐");
        //生成图片数
        json.set("n",2);
        //生成图片大小
        json.set("size","1024x1024");
        //返回格式
        json.set("response_format","url");

        //发送请求
        HttpResponse response = HttpRequest.post("https://api.openai.com/v1/images/generations")
                .headerMap(headers, false)
                .bearerAuth("填写自己注册的token")
                .body(String.valueOf(json))
                .timeout(5 * 60 * 1000)
                .execute();

        System.out.println(response.body());
    }
}

// output result

{
    
    
  "created": 1671269880,
  "data": [
    {
    
    
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-pdYv7jlVgMVLo21vFtr0RmLC/user-dWUudL2WFYo8MmkaYdTadc03/img-8fkcdDDEmpvI2ZedT6ddpig2.png?st=2022-12-17T08%3A38%3A00Z&se=2022-12-17T10%3A38%3A00Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2022-12-17T04%3A00%3A10Z&ske=2022-12-18T04%3A00%3A10Z&sks=b&skv=2021-08-06&sig=R7CiMZmMatTXE2%2B0hyQqypUBFKPlubggA2IIA9zBCQQ%3D"
    },
    {
    
    
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-pdYv7jlVgMVLo21vFtr0RmLC/user-dWUudL2WFYo8MmkaYdTadc03/img-JQl7Hor0vzScGEMSvhlnAWOd.png?st=2022-12-17T08%3A38%3A00Z&se=2022-12-17T10%3A38%3A00Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2022-12-17T04%3A00%3A10Z&ske=2022-12-18T04%3A00%3A10Z&sks=b&skv=2021-08-06&sig=y3j8QuYD%2Bzmym6DHrfJpLrutGDZGtbjKsug4O/kQpQ8%3D"
    }
  ]
}

We put the url returned by the above call into the address bar of the browser to view the picture. Do not set too large "n" in the interface parameter, sometimes the returned picture, how to say it. The aesthetics of ai may not be the same as ours, but the first url is okay hahaha~(●'◡'●)

7 Summary

The above example shows that it is very simple for Java to call the ChatGpt interface. If you encounter any problems, you can pay attention to the official account at the end of the article for consultation (●'◡'●)
Simple and simple, but each request costs money, I don’t know how long $18 can last.
After a wave of test calls, it cost $0.27, which is equivalent to ¥1.88 in Renminbi. Please save some calls, it will not be cheap in the long run.

insert image description here
This is the end of the content of this issue. Friends, we will see you in the next issue (●'◡'●)

Guess you like

Origin blog.csdn.net/rong0913/article/details/128350990