OpenAIChatGptUtil.java 2.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package com.kwan.springbootkwan.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.kwan.springbootkwan.entity.chat.ChoiceMessage;
import com.kwan.springbootkwan.entity.chat.Choices;
import com.kwan.springbootkwan.entity.chat.CompletionChatRequest;
import com.kwan.springbootkwan.entity.chat.CompletionChatResponse;

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

/**
17
 * chatgpt-api
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
 *
 * @author : qinyingjie
 * @version : 2.2.0
 * @date : 2023/3/22 20:40
 */
public class OpenAIChatGptUtil {
    /**
     * 请求地址
     */
    final static private String chatCompletionUrl = "https://api.openai.com/v1/chat/completions";
    /**
     * 模型
     */
    final static private String model = "gpt-3.5-turbo";
    /**
     * 这里使用你自己的认证信息
     */
    final static private String Authorization = "Bearer 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";

    public static void main(String[] args) {
        String question = "默写静夜思";
        //这里是我根据模型请求封装的模型实体
        CompletionChatRequest completionChatRequest = new CompletionChatRequest();
        //封装http请求
        HttpRequest post = HttpUtil.createPost(chatCompletionUrl).timeout(300000);
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", Authorization);
        post.addHeaders(headers);
        post.contentType("application/json;charset=UTF-8");
        completionChatRequest.setModel(model);
        ChoiceMessage message = new ChoiceMessage("user", question);
        List<Object> messages = new ArrayList<>();
        messages.add(message);
        completionChatRequest.setMessages(messages);
        post.body(JSON.toJSONString(completionChatRequest));
        String body = post.execute().body();
        CompletionChatResponse completionChatResponse = JSON.parseObject(body, CompletionChatResponse.class);
        final List<Choices> choices = completionChatResponse.getChoices();
        for (Choices choice : choices) {
            final ChoiceMessage message1 = choice.getMessage();
            final String content = message1.getContent();
            System.out.println(content);
        }
        System.out.println("成功");
    }
}