当前位置: 代码网 > it编程>编程语言>Java > SpringBoot接入deepseek深度求索示例代码(jdk1.8)

SpringBoot接入deepseek深度求索示例代码(jdk1.8)

2025年02月13日 Java 我要评论
以下是在springboot中接入aideepseek的过程。我这里的环境是jdk1.8,官网暂时没有java的示例。1. 创建apikeydeepseek api keys新用户会有500万的免费t

以下是在springboot中接入ai deepseek的过程。我这里的环境是jdk1.8,官网暂时没有java的示例。

1. 创建 api key 

deepseek api keys 

新用户会有500万的免费token额度

2. 封装询问deepseek的工具方法

添加key值和询问路径。api_key为你创建的key值。这个在配置文件或者是写在常量文件都可以,我这是写在配置文件里了

接下来就是代码实例了

import com.fasterxml.jackson.databind.jsonnode;
import com.fasterxml.jackson.databind.objectmapper;
import com.zhiwonders.paperserver.service.iauthservice;
import lombok.extern.slf4j.slf4j;
import org.apache.http.client.methods.closeablehttpresponse;
import org.apache.http.client.methods.httppost;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclients;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.value;
import org.springframework.http.mediatype;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.sseemitter;
import java.io.bufferedreader;
import java.io.inputstreamreader;
import java.nio.charset.standardcharsets;
import java.util.collections;
import java.util.hashmap;
import java.util.map;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;


@restcontroller
@requestmapping("/api/v1")
@slf4j
public class openaicontroller {

    @value("${ai.config.deepseek.apikey}")
    private string api_key;

    @value("${ai.config.deepseek.baseurl}")
    private string api_url;

    @autowired
    private iauthservice authservice;

    private final executorservice executorservice = executors.newcachedthreadpool();
    private final objectmapper objectmapper = new objectmapper();

    @postmapping(value = "/chat", produces = mediatype.text_event_stream_value)
    public sseemitter chat(
//            @requestheader("authorization")string token,
                           @requestbody string question) {
//        string openid = authservice.openid(token);
//        if (openid == null) {
//            throw new runtimeexception("用户未登录");
//        }
        sseemitter emitter = new sseemitter(-1l);
        executorservice.execute(() -> {
            try {
                log.info("流式回答开始,问题:{}", question);
                try (closeablehttpclient client = httpclients.createdefault()) {
                    httppost request = new httppost(api_url);
                    request.setheader("content-type", "application/json");
                    request.setheader("authorization", "bearer " + api_key);

                    map<string, object> message = new hashmap<>();
                    message.put("role", "user");
                    message.put("content", question);

                    map<string, object> requestmap = new hashmap<>();
                    requestmap.put("model", "deepseek-chat");
                    requestmap.put("messages", collections.singletonlist(message));
                    requestmap.put("stream", true);

                    string requestbody = objectmapper.writevalueasstring(requestmap);
                    request.setentity(new stringentity(requestbody, standardcharsets.utf_8));

                    try (closeablehttpresponse response = client.execute(request);
                         bufferedreader reader = new bufferedreader(
                                 new inputstreamreader(response.getentity().getcontent(), standardcharsets.utf_8))) {
                        string line;
                        while ((line = reader.readline()) != null) {
                            if (line.startswith("data: ")) {
                                string jsondata = line.substring(6);
                                if ("[done]".equals(jsondata)) {
                                    break;
                                }
                                jsonnode node = objectmapper.readtree(jsondata);
                                string content = node.path("choices")
                                        .path(0)
                                        .path("delta")
                                        .path("content")
                                        .astext("");
                                if (!content.isempty()) {
                                    emitter.send(content);
                                }
                            }
                        }
                        log.info("流式回答结束,{}",question);
                        emitter.complete();
                    }
                } catch (exception e) {
                    log.error("处理 deepseek 请求时发生错误", e);
                    emitter.completewitherror(e);
                }
            } catch (exception e) {
                log.error("处理 deepseek 请求时发生错误", e);
                emitter.completewitherror(e);
            }
        });
        return emitter;
    }
}

3.调用测试

curl -v -x post \
    http://localhost:8091/api/v1/chat \
    -h "content-type: application/json" \
    -d '"帮我写一篇2000字的 我的祖国的文字"' \
    --no-buffer

打开终端输入上述命令回车即可 但是端口必须要和你后端的一致 我这里是8091

4.运行结果

总结 

到此这篇关于springboot接入deepseek深度求索的文章就介绍到这了,更多相关springboot接入deepseek深度求索内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com