springboot调用DeepSeek

199 阅读2分钟

springboot使用WebClient流式集成deepSeek

一、定义需要使用的ApiKey和基础url

@Value("${spring.ai.openai.api-key}")
private String apiKey;

@Value("${spring.ai.openai.base-url}")
private String baseUrl;
//记录历史回答,实现多轮问答
private List<DeepSeekMessage> historyList = new ArrayList<>();

二、封装请求参数实体类

//记录用户问题和AI回答类
class DeepSeekMessage{
private String role;

private String content;

public String getRole() {
    return role;
}

public void setRole(String role) {
    this.role = role;
}

public String getContent() {
    return content;
}

public void setContent(String content) {
    this.content = content;
}

public DeepSeekMessage(String role, String content) {
    this.role = role;
    this.content = content;
}

public DeepSeekMessage() {
}
}
//请求实体类
class DeepSeekRequest{
 private String model = "deepseek-r1";
 private boolean stream = true;
 private List<DeepSeekMessage> messages;

public String getModel() {
    return model;
}

public void setModel(String model) {
    this.model = model;
}

public boolean isStream() {
    return stream;
}

public void setStream(boolean stream) {
    this.stream = stream;
}

public List<DeepSeekMessage> getMessages() {
    return messages;
}

public void setMessages(List<DeepSeekMessage> messages) {
    this.messages = messages;
}
}

三、流式请求



@GetMapping("/test5")
public void chat5(String msg, HttpServletResponse response){
    WebClient webClient = WebClient.create(baseUrl);
    DeepSeekMessage deepSeekMessage = new DeepSeekMessage("user", msg);
    historyList.add(deepSeekMessage);
    DeepSeekRequest deepSeekRequest = new DeepSeekRequest();
    deepSeekRequest.setMessages(historyList);

    webClient.post()
            .uri("/chat/completions")
            .header("Content-Type","application/json")
            .header("Authorization","Bearer "+apiKey)
            .bodyValue(deepSeekRequest)
            .retrieve()
            .bodyToFlux(String.class)
            .subscribe(resp->{
            if(!"[DONE]".equals(resp)){
                JSONObject jsonObject = JSONUtil.parseObj(resp);
                JSONObject deltaObject = jsonObject.getJSONArray("choices").getJSONObject(0);
                JSONObject object = deltaObject.getJSONObject("delta");
                //推理或者表示停止的key
                if(object.containsKey("reasoning_content")){
                    String content = object.getStr("reasoning_content");
                    if("\n".equals(content) || "\n\n".equals(content)){
                        System.out.println();
                    }else {
                        System.out.print(content);
                    }
                }else{
                    String content = object.getStr("content");
                    if("\n".equals(content) || "\n\n".equals(content)){
                        System.out.println();
                    }else {
                        System.out.print(content);
                        historyList.add(new DeepSeekMessage("assistant",content));
                    }
                }
            }
            });
}
}

使用 deepseek4j集成deepseek

一、引入依赖

 <dependency>
    <groupId>io.github.pig-mesh.ai</groupId>
    <artifactId>deepseek-spring-boot-starter</artifactId>
    <version>1.4.3</version>
</dependency>

二、配置基本信息

deepseek:
  api-key: xxx
  base-url: xxx
  model: xxx
  search-api-key: sk-d42b00c65bd5465dafecf261fa005afb #联网搜索时的的APIKEY

三、流式请求

 private List<String> historyList = new ArrayList<>();

    //流式+多轮对话
    @GetMapping(value="/chat/advanced",produces = MediaType.TEXT_EVENT_STREAM_VALUE+";charset=UTF-8")
    public Flux<ChatCompletionResponse> chat2(String prompt){
        StringBuilder hsitoryMsg = new StringBuilder();
        ChatCompletionRequest request = ChatCompletionRequest.builder()
                //模型选择
                //.model(ChatCompletionModel.DEEPSEEK_REASONER)
                //系统消息设置角色和行为
                .addSystemMessage("你是一个专业的助手")
                //默认为2048
                .maxTokens(2048)
                //设置温度
                .temperature(0.6)
                //上一轮的对话结果
                .addAssistantMessage(historyList.toString())
                //用户信息
                .addUserMessage(prompt)
                .build();


      return deepSeekClient.chatFluxCompletion(request)

              .doOnNext(response->{
                  //本次的请求用量分析
                  //System.out.println(response.usage());
                  List<ChatCompletionChoice> choices = response.choices();
                  ChatCompletionChoice chatCompletionChoice = choices.get(0);
                  Delta delta = chatCompletionChoice.delta();
                  if("stop".equals(chatCompletionChoice.finishReason())){
                      System.out.println("本次回答结束");
                      historyList.add(hsitoryMsg.toString());
                  }
                  //回答
                  if(StrUtil.isNotEmpty(delta.content()) && !"\n\n".equals(delta.content())){
                      System.out.println(delta.content());
                      hsitoryMsg.append(delta.content());
                  }
                  //思维
                  if(StrUtil.isNotEmpty(delta.reasoningContent()) && !"\n\n".equals(delta.reasoningContent())){
                      System.out.println(delta.reasoningContent());
                  }
              });
    }