Java SpringBoot implements the related interface for calling OpenAI ChatGPT (detailed tutorial)

outline

illustrate

Java calls the OpenAI interface, Java calls to implement ChatGPT chat, OpenAIAPI is a Java tool class of the OpenAI GPT-3 chat API packaged by itself, which can be used to call the GPT-3 model through Java code for natural language interaction, and realize smart chat and other functions.
By calling the GPT-3 model, input a piece of text, and return the text of the robot's dialogue reply.
Attached project code: at the end of this article

OpenAI3.5 model version uses

Tools

Lombok and hutool dependencies are used

The following is the tool class encapsulated by myself, just write your own api and you can use it


import cn.hutool.core.convert.ConvertException;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Astar
 * ClassName:OpenAIAPI.java
 * date:2023-03-03 16:49
 * Description:
 */
@UtilityClass
public class OpenAIAPI {
    
    
    /**
     * 聊天端点
     */
    String chatEndpoint = "https://api.openai.com/v1/chat/completions";
    /**
     * api密匙
     */
    String apiKey = "Bearer 你自己的key";

    /**
     * 发送消息
     *
     * @param txt 内容
     * @return {@link String}
     */
    public String chat(String txt) {
    
    
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("model", "gpt-3.5-turbo");
        List<Map<String, String>> dataList = new ArrayList<>();
        dataList.add(new HashMap<String, String>(){
    
    {
    
    
            put("role", "user");
            put("content", txt);
        }});
        paramMap.put("messages", dataList);
        JSONObject message = null;
        try {
    
    
            String body = HttpRequest.post(chatEndpoint)
                .header("Authorization", apiKey)
                .header("Content-Type", "application/json")
                .body(JsonUtils.toJson(paramMap))
                .execute()
                .body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            JSONArray choices = jsonObject.getJSONArray("choices");
            JSONObject result = choices.get(0, JSONObject.class, Boolean.TRUE);
            message = result.getJSONObject("message");
        } catch (HttpException e) {
    
    
            return "出现了异常";
        } catch (ConvertException e) {
    
    
            return "出现了异常";
        }
        return message.getStr("content");
    }

    public static void main(String[] args) {
    
    
        System.out.println(chat("Hello,一个小浪吴啊"));
    }
}

Parameter description:
txt: the text content to be sent.
Return value: The reply text of the bot.

test

Precautions

  1. Before using OpenAI API, you need to register an account on the OpenAI official website and obtain an API key.
  2. Before using the chat method, you need to modify the chatEndpoint and apiKey variables in OpenAIAPI to specify the URL and key of the API respectively.
  3. Before using the chat method, it is necessary to determine the GPT-3 model and parameters used.
  4. When using the chat method, you need to pay attention to the length and format of the text content, as well as the stability and speed of the network connection.

code description

This code is a Java tool class, which is used to access OpenAI's API interface for chatting. Here are some important technical notes:

  1. The Java Lombok tool class is used to provide the @UtilityClass annotation, making the class a non-instantiable tool class.
  2. Two constants chatEndpoint and apiKey of String type are defined, representing OpenAI's chat API endpoint and API key respectively.
  3. A chat method is defined, which is used to send chat messages to the API interface of OpenAI, and the input parameter is txt, which represents the chat content.
  4. The third-party Java tool class Hutool is used for HTTP request and JSON data parsing. Among them, the HttpRequest.post() method is used to send a POST request, the JsonUtils.toJson() method is used to convert the parameter paramMap into a string in JSON format, and the JSONUtil.parseObj() method is used to parse the JSON string returned by the interface into JSONObject object.
  5. When sending a request, encapsulate the request parameters as a Map object, where the model attribute represents the GPT model used, and the messages attribute is a List object, which contains a HashMap object representing the user's chat messages.
  6. After sending the request, get the message returned by the chatbot from the JSON data returned by the interface, and then use the content attribute of the message as the return value of the method.
  7. In the exception handling, the exception classes HttpException and ConvertException provided by Hutool are used to handle exceptions.

In general, this code uses Java's Hutool tool class to send HTTP requests and parse JSON data, thus realizing the function of chatting through OpenAI API.

epilogue

Project address: https://gitee.com/wy521a/astar-weixin-mp

Integrated official account use: https://gitee.com/wy521a/astar-weixin-mp

Guess you like

Origin blog.csdn.net/A_yonga/article/details/129398716