调用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);
    }
}
相关推荐
霖雨3 小时前
使用Visual Studio Code 快速新建Net项目
java·ide·windows·vscode·编辑器
唐宋元明清21883 小时前
Surface pro 11二合一平板参数调研
windows·外设
ZIM学编程3 小时前
Java基础Day-Sixteen
java·开发语言·windows
Ling-X59 小时前
红日靶机(七)笔记
linux·windows·内网渗透·靶机笔记·vulnstack
文人sec12 小时前
泷羽sec学习打卡-Windows基础virus
windows·学习·安全·web安全·php
曙曙学编程13 小时前
初级数据结构——单向链表
数据结构·windows·链表
知来者逆16 小时前
基于ChatGPT 的人工智能代理挖掘化学文献的演变探索
人工智能·gpt·语言模型·自然语言处理·chatgpt·gpt-4v
zhyjhacker16 小时前
4.1 WINDOWS XP,ReactOS对象与对象目录----1
windows
funnycoffee12317 小时前
Windows bat批处理实现文本复制到剪贴板
windows·windows批处理
N0zoM1z018 小时前
2024 西湖论剑 Reverse BabyCPP
windows