it编程 > 编程语言 > Java

Java调用DeepSeek实现多轮对话功能

5人参与 2025-03-09 Java

背景

近期deepseek比较火,很多小伙伴尝试用各种语言调用deepseek,最近刚好也有些兴趣,写了一版关于适用java调用deepseek的代码供小白使用。

效果

1.创建api keys

登陆deepseek开放平台deepseek开放平台创建api key

2.参考官网调用文档

地址对话补全 | deepseek api docs

3.多轮对话

代码

最后附上代码,感兴趣的小伙伴可以拿去玩玩

package com.ssc.gdh.phbc.data.serve.strategy.layer;
 
import com.alibaba.fastjson.jsonarray;
import com.alibaba.fastjson.jsonobject;
import com.alibaba.fastjson2.json;
import okhttp3.*;
import org.apache.commons.lang3.stringutils;
 
import java.io.ioexception;
import java.util.scanner;
import java.util.concurrent.timeunit;
 
public class deepseek {
 
    public static void main(string[] args) throws ioexception {
        scanner scanner = new scanner(system.in);
        jsonarray chat = null;
        while (true){
            system.out.print("与deepseek对话,请输入内容(输入 'exit' 退出):");
            string msg = scanner.nextline(); // 读取一行输入
            okhttpclient client = new okhttpclient().newbuilder()
                    .connecttimeout(10, timeunit.seconds) // 连接超时时间
                    .readtimeout(300, timeunit.seconds)    // 读取超时时间
                    .writetimeout(300, timeunit.seconds)   // 写入超时时间
                    .build();
            // 检查是否退出
            if ("exit".equalsignorecase(msg)) {
                system.out.println("程序已退出。");
                break; // 退出循环
            }
            chat = sendmessage(client, msg, chat);
        }
    }
 
    private static jsonarray sendmessage(okhttpclient client,string question,jsonarray chat) {
        mediatype mediatype = mediatype.parse("application/json");
        jsonobject param = new jsonobject();
        param.put("model","deepseek-chat");
        param.put("frequency_penalty",0);
        param.put("presence_penalty",0);
        jsonarray messages = chat;
 
        if (messages == null){
            messages = new jsonarray();
            jsonobject o1 = new jsonobject();
            o1.put("role","user");
            o1.put("content",question);
            messages.add(o1);
        }else {
            jsonobject o1 = new jsonobject();
            o1.put("role","user");
            o1.put("content",question);
            messages.add(o1);
        }
        param.put("messages",messages);
 
 
//        requestbody body = requestbody.create(mediatype, string.format("{\n  \"messages\": [\n    {\n      \"content\": \"%s\"," +
//                "\n      \"role\": \"user\"\n    },\n    {\n      \"content\": \"%s\",\n      \"role\": \"user\"\n    }\n  ],\n  \"model\": \"deepseek-chat\",\n  \"frequency_penalty\": 0,\n  \"max_tokens\": 2048," +
//                "\n  \"presence_penalty\": 0,\n  \"response_format\": {\n    \"type\": \"text\"\n  },\n  \"stop\": null,\n  \"stream\": false," +
//                "\n  \"stream_options\": null,\n  \"temperature\": 1,\n  \"top_p\": 1,\n  \"tools\": null,\n  \"tool_choice\": \"none\",\n  \"logprobs\": false,\n  \"top_logprobs\": null\n}",question,question1));
 
        requestbody body = requestbody.create(mediatype, json.tojsonstring(param));
        request request = new request.builder()
                .url("https://api.deepseek.com/chat/completions")
                .method("post", body)
                .addheader("content-type", "application/json")
                .addheader("accept", "application/json")
                .addheader("authorization", "bearer 你的api_keys")//你申请的api_keys
                .build();
        try (response response = client.newcall(request).execute()) {
            if (response.issuccessful()) {
                responsebody responsebody = response.body();
                if (responsebody != null) {
                    // 将响应体转换为字符串
                    string responsestring = responsebody.string();
                    jsonobject jsonobject = jsonobject.parseobject(responsestring);
                    jsonarray choices = jsonarray.parsearray(jsonobject.getstring("choices"));
                    string content = jsonobject.parseobject(jsonobject.parseobject(choices.get(0).tostring()).get("message").tostring()).get("content").tostring();
                    if (stringutils.isnotblank(content)){
                        jsonobject o1 = new jsonobject();
                        o1.put("role","assistant");
                        o1.put("content",content);
                        messages.add(o1);
                    }
                    system.out.println(content);
                    return messages;
                }
            } else {
                system.out.println("request failed with code: " + response.code());
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
        return null;
    }
}
 

到此这篇关于java调用deepseek实现多轮对话功能的文章就介绍到这了,更多相关java deepseek多轮对话内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

Java使用OpenCV进行图像处理的示例代码

03-09

SpringBoot整合Logback日志框架及高并发下的性能优化

03-09

使用Java连接WMI获取系统信息的方法

03-09

Java利用Jsoup解析和操作HTML的技术指南

03-10

SpringBoot自定义注解如何解决公共字段填充问题

03-10

使用EasyPOI实现多sheet动态列导出

03-10

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论