From 0 to 1, use chatGPT and simply call JAVA api to realize web page interaction.

Preface

  This article discusses from 0 to 1, how to register a GPT account, how to write prompts (prompt), and simple examples of simple java calling api. If you are interested in GPT but don’t know how to get started, you can read it. Next this article

Registration process

1. You can access the official website normally: https://openai.com/
2. Prepare an available foreign email address such as gmail, microsoft email, etc. Up to now, qq mailbox, 163 and other domestic mailboxes are all unavailable.
3. Prepare an available mobile phone that accepts the verification code (for example, through: sms-active)

  The following is a screenshot of the registration process. The Indian mobile phone number I am currently using can be used for personal testing.

Insert image description here
Insert image description here
4. Log in to the GPT official website, click register, use an overseas email address, and the mobile phone number you purchased. After verification via SMS, you can use GPT3.5 normally.
Insert image description here

How to make prompt words more accurate?

  As shown in the description on the official website, there are the following 6 basic testing strategies. For example:

Bad prompt: Please give me a paragraph describing a car.
Good prompt: Please give me a Chinese paragraph describing a Porsche sports car. The article should be about 50 words.

  To put it simply, it is to provide more accurate information, so that the large model will have better corresponding matching information, rather than letting AI guess what you want.
Insert image description here

Simple call to api

Insert image description here

  Friends who see here must have guessed that it is to send a specific format of http request to the open-ai server, and then we parse or display the information respond gives us, so next let’s take a look at open-ai Roughly what interfaces are provided, and how to write a java program to request these interfaces

  Prerequisite: Apply for key sk
Insert image description here

Use httpclient to manually fill in request headers

  The first is to manually use HttpClients to build the request object. Of course, the pom needs to introduce the dependency of httpclient.

       <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>XXX</version>
        </dependency>
//问:请告诉我java序列化的方式
    @RequestMapping("/chat")
    public void streamChat()throws IOException {
    
    
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
    
    
            HttpPost httpPost = new HttpPost("https://api.openai.com/v1/chat/completions");

            StringEntity requestEntity = new StringEntity(
                    "{\"model\": \"gpt-3.5-turbo\",\"messages\": [{ \"role\" : \"user\" , \"content\":  \"请告诉我java序列化的方式\"}], \"temperature\": 0.7, \"max_tokens\": 100}",
                    "UTF-8"
            );

            requestEntity.setContentType("application/json");
            //如果有用梯子 代理的端口 ip  
            HttpHost proxy = new HttpHost("代理ip", 代理端口);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setProxy(proxy)
                    .setConnectTimeout(10000)
                    .setSocketTimeout(10000)
                    .setConnectionRequestTimeout(3000)
                    .build();

            httpPost.setConfig(requestConfig);
            httpPost.setEntity(requestEntity);

            httpPost.addHeader("Authorization", "Bearer sk-你的密钥");
            httpPost.addHeader("Content-Type", "application/json");

            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
    
    
                HttpEntity entity = response.getEntity();
                if (entity != null) {
    
    
                    String result = EntityUtils.toString(entity);
                    System.out.println(result);
                }
            } finally {
    
    
                response.close();
            }
        } finally {
    
    
            httpclient.close();
        }

    }

Ready-made packaging methods

For example, the java community package TheoKanning/openai-java   specified on the official website

Insert image description here

  I found a better and more concise package packaged by a friend. This is his project link:
https://github.com/asleepyfish/chatgpt
  . You can try it, introduce the dependencies of this project, and then test it.

    @RestController
    public class ChatGPTController {
    
    
        @GetMapping("/downloadImage")
        public void downloadImage(String prompt, HttpServletResponse response) {
    
    
            OpenAiUtils.downloadImage(prompt, response);
        }
    }

    @GetMapping("/streamChatWithWeb")
    public void streamChatWithWeb(String content, HttpServletResponse response) throws IOException {
    
    
        // 需要指定response的ContentType为流式输出,且字符编码为UTF-8
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        OpenAiUtils.createStreamChatCompletion(content, response.getOutputStream());
    }

final effect

Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_44716086/article/details/131849308