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; /** * chatgpt-api * * @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 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 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 = completionChatResponse.getChoices(); for (Choices choice : choices) { final ChoiceMessage message1 = choice.getMessage(); final String content = message1.getContent(); System.out.println(content); } System.out.println("成功"); } }