调用Deepseek接口
调用Deepseek接口

调用Deepseek接口

毕设上准备加入点AI相关的创新点,原本想用协同过滤算法的,但是感觉还是大模型更吸引眼球,就调用了一下API玩一玩。

配置文件key和url。创建config.properties配置文件

key = sk-9bb09bc11727402ba405bb3289aa11b4
url = https://api.deepseek.com/chat/completions

打印返回体

public class TypewriterEffect {
    public static void printWord(String text,int delay){
        for(int i = 0; i < text.length(); i++){
            //打印单个字符
            System.out.print(text.charAt(i));
            //立刻刷新输出缓冲区
            try{
                //控制打印速度
                Thread.sleep(delay);
            }catch (Exception e){
                System.out.println("打印被中断");
                return ;
            }
       }
        System.out.println();
    }
}

从配置文件中读取key和url。添加配置文件的目的是为了充分解耦。

    private static String API_KEY;
    private static String API_URL;
    //从配置文件中获取key和url
    static {
        Properties properties = new Properties();
        try{
            InputStream is = DeepSeekClient.class.getClassLoader().getResourceAsStream("config.properties");
            properties.load(is);
            API_KEY = properties.getProperty("key");
            API_URL = properties.getProperty("url");
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

运行类

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = "";
        System.out.println("请提问");
        while(true){
            String question = scanner.next();
            if(question.equals("exit")){
                break;
            }
            ask(question);//询问
            System.out.println();
        }
    }

请求响应类的结构

 //定义内部类请求响应结构
    static class Message{
        private String content;
        private String role;
        public Message(String content, String role) {
            this.content = content;
            this.role = role;
        }
        public String getContent() {
            return content;
        }
    }

请求体

//请求体
    static class ChatRequest{
        private String model;
        private List<Message> messages;
        private double temperature;
        private int max_tokens;
        public ChatRequest(String model, List<Message> messages, double temperature, int max_tokens) {
            this.model = model;
            this.messages = messages;
            this.temperature = temperature;
            this.max_tokens = max_tokens;
        }
    }

响应体

 //响应体
    static class ChatResponse{
        private List<Choice> choices;
        public List<Choice> getChoices() {
            return choices;
        }
        static class Choice{
            private Message message;
            public Message getMessage() {
                return message;
            }
        }
    }

询问方法

public static void ask(String content) {
        //创建消息列表
        List<Message> messages = new ArrayList<>();
        messages.add(new Message(content,"user"));
        ChatRequest requestBody = new ChatRequest(
                "deepseek-chat",//配置模型
                messages,
                0.7,
                1000
        );
        System.out.println("正在提交问题");
        long start = System.currentTimeMillis();
        //发送请求
        String response = sendRequest(requestBody);
        long endTime = System.currentTimeMillis();
        System.out.println("思考时间: "+ (endTime - start) + "毫秒");//计算响应时间
        TypewriterEffect.printWord(response,0);//在控制栏打印结果
    }

发送请求方法

private static String sendRequest(ChatRequest requestBody){
        HttpClient client = HttpClient.newHttpClient();
        Gson gson = new Gson();
        //将ChatRequest 对象中封装的数据转为JSON格式
        String requestBodyJson = gson.toJson(requestBody);
        try{
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(API_URL))//配置url
                    .header("Content-Type","application/json")
                    .header("Authorization","Bearer "+API_KEY)//配置key
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyJson))//将返回数据转成json格式
                    .build();
            System.out.println("问题以提交,正在思考中");
            HttpResponse<String> response = client.send(request,HttpResponse.BodyHandlers.ofString());
            if(response.statusCode() == 200){
                ChatResponse chatResponse = gson.fromJson(response.body(),ChatResponse.class);
                return chatResponse.getChoices().get(0).getMessage().getContent();
            }else{
                return "请求失败,状态码: " + response.statusCode()+" ,响应: "+response.body();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "请求异常:" +  e.getMessage();
        }
    }

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注