调用chat-gpt

调用chat-gpt

依赖

java 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

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

相关的类

java 复制代码
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

 
@Data
public class ChatRequest {

    private String model;
    private List<Message> messages;
    private int n = 3;
    private double temperature = 0.2;

    public ChatRequest(String model, String prompt) {
        this.model = model;

        this.messages = new ArrayList<>();
//        this.messages.add(new Message("system", "You are a IELTS Teachers."));
        this.messages.add(new Message("system", "You are an IELTS teacher, and your answers are all in JSON string format."));
        this.messages.add(new Message("user", prompt));
    }

    public ChatRequest(String model, List<String> prompts) {
        this.model = model;

        this.messages = new ArrayList<>();
        for (String prompt : prompts) {
            this.messages.add(new Message("user", prompt));
        }
    }

}
javaj 复制代码
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
 
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ChatResponse {

    private List<Choice> choices;

    public static class Choice {

        private int index;
        private Message message;

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public Message getMessage() {
            return message;
        }

        public void setMessage(Message message) {
            this.message = message;
        }
    }

}
java 复制代码
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * JSON 工具类
 * 
 */
@UtilityClass
@Slf4j
public class JsonUtils {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.registerModules(new JavaTimeModule()); // 解决 LocalDateTime 的序列化
    }

    /**
     * 初始化 objectMapper 属性
     * <p>
     * 通过这样的方式,使用 Spring 创建的 ObjectMapper Bean
     *
     * @param objectMapper ObjectMapper 对象
     */
    public static void init(ObjectMapper objectMapper) {
        JsonUtils.objectMapper = objectMapper;
    }

    @SneakyThrows
    public static String toJsonString(Object object) {
        return objectMapper.writeValueAsString(object);
    }

    @SneakyThrows
    public static byte[] toJsonByte(Object object) {
        return objectMapper.writeValueAsBytes(object);
    }

    @SneakyThrows
    public static String toJsonPrettyString(Object object) {
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
    }

    public static <T> T parseObject(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        try {
            return objectMapper.readValue(text, clazz);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 将字符串解析成指定类型的对象
     * 使用 {@link #parseObject(String, Class)} 时,在@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) 的场景下,
     * 如果 text 没有 class 属性,则会报错。此时,使用这个方法,可以解决。
     *
     * @param text 字符串
     * @param clazz 类型
     * @return 对象
     */
    public static <T> T parseObject2(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        return JSONUtil.toBean(text, clazz);
    }

    public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
        if (ArrayUtil.isEmpty(bytes)) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, clazz);
        } catch (IOException e) {
            log.error("json parse err,json:{}", bytes, e);
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(text, typeReference);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    public static JsonNode parseTree(String text) {
        try {
            return objectMapper.readTree(text);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    public static JsonNode parseTree(byte[] text) {
        try {
            return objectMapper.readTree(text);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }


}
java 复制代码
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

 
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message {

    private String role;

    private String content;

}
java 复制代码
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;


public class Dome {
    public static void main(String[] args) {
        String model = "gpt-3.5-turbo";
        String prompt = "你好,说一下女娲补天的故事";
        String openAiApiKey = "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";
        ChatRequest request = new ChatRequest(model, prompt);
        String url = "https://api.openai-proxy.com/v1/chat/completions";
        String json = JsonUtils.toJsonString(request);
        String result = HttpRequest.post(url)
                .header("Authorization", "Bearer " + openAiApiKey)
                .header("Content-Type", "application/json")
                .body(json)
                .execute()
                .body();
        System.out.println(result);
        if ( result==null) {
            System.out.println("错误");
        }
        ChatResponse response = JSONUtil.toBean(result, ChatResponse.class);
        System.out.println(response);
    }
}
相关推荐
Tasfa32 分钟前
【AI系列】从零开始学习大模型GPT (1)- Build a Large Language Model (From Scratch)
人工智能·gpt·学习
love530love3 小时前
Windows 11 中利用 WSL - Linux 虚拟环境部署 ChatTTS-Enhanced 项目教程
linux·运维·windows
kaixin_啊啊3 小时前
Windows电脑异地SSH远程连接苹果MacOS小主机Mac mini详细教程
windows·macos·ssh
AI明说4 小时前
DDI-GPT:使用知识图谱增强的大模型对药物相互作用进行可解释的预测
人工智能·gpt·大模型·知识图谱·数智药师·数智药学
xuexixuexien5 小时前
.NetCore WebAPI 导入、导出Excel文件
windows·excel·.netcore
码农君莫笑9 小时前
《信管通低代码信息管理系统开发平台》Windows环境安装说明
服务器·数据库·windows·低代码·c#·bootstrap·.netcore
葡萄架子12 小时前
用Python写炸金花游戏
windows·python·游戏
小言从不摸鱼14 小时前
【AI大模型】探索GPT模型的奥秘:引领自然语言处理的新纪元
人工智能·gpt·深度学习·语言模型·自然语言处理·transformer
广而不精zhu小白1 天前
CentOS Stream 9 挂载Windows共享FTP文件夹
linux·windows·centos
逸_1 天前
dify工作流+github actions实现翻译并创建PR
gpt·github·dify