SpringBoot接入DeepSeek,保姆级教程

1、创建 API key

创建链接:

https://platform.deepseek.com/api_keys

SpringBoot接入DeepSeek,保姆级教程_第1张图片

点击创建 API key 即可免费生成一个key值,别忘记保存。

2、java端接入

  • 完整目录

SpringBoot接入DeepSeek,保姆级教程_第2张图片

  • springboot配置文件 application.yml
    ai:
      config:
        deepseek:
          apiKey: 填写官网申请的Key
          baseUrl: https://api.deepseek.com/chat/completions
    server:
      port: 8080
    spring:
      thymeleaf:
        prefix: classpath:/templates/
        suffix: .html

  • pom文件


    4.0.0
    com.chat
    chat_demo
    0.0.1-SNAPSHOT
    chat_demo
    chat_demo
    
        1.8
        UTF-8
        UTF-8
        2.6.13
    
    

        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            cn.hutool
            hutool-all
            5.8.35
        
        
        
            org.projectlombok
            lombok
            1.18.30
            provided
        


        
        
            com.squareup.okhttp3
            okhttp
            4.9.0
        



        
            com.mashape.unirest
            unirest-java
            1.4.9
        
        
            org.apache.httpcomponents
            httpclient
            4.3.6
        
        
            org.apache.httpcomponents
            httpasyncclient
            4.0.2
        
        
            org.apache.httpcomponents
            httpmime
            4.3.6
        
        
            org.projectlombok
            lombok
            provided
        
    
    
        
            
                org.springframework.boot
                spring-boot-dependencies
                ${spring-boot.version}
                pom
                import
            
        
    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.8.1
                
                    1.8
                    1.8
                    UTF-8
                
            
            
                org.springframework.boot
                spring-boot-maven-plugin
                ${spring-boot.version}
                
                    com.chat.chat_demo.ChatDemoApplication
                    true
                
            
        
    


  • controller接口
package com.chat.chat_demo.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
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.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@RestController
@RequestMapping("deepSeek")
@Slf4j
public class OpenAIController {

    @Value("${ai.config.deepseek.apiKey}")
    private String API_KEY;

    @Value("${ai.config.deepseek.baseUrl}")
    private String API_URL;

    // 用于保存每个用户的对话历史
    //https://api.deepseek.com/chat/completions 此接口为无状态接口,需要上下文连贯对话需要将历史聊天记录一并发送至接口中
    private final Map>> sessionHistory = new ConcurrentHashMap<>();

    private final ExecutorService executorService = Executors.newCachedThreadPool();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping()
    public ModelAndView chat(ModelAndView modelAndView) {
        modelAndView.setViewName("chat");
        return modelAndView;
    }


    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chat(
//            @RequestHeader("Authorization") String token,
            @RequestBody String question) {
        // 假设 token 是用户的唯一标识
//        String userId = token; // 或者从 token 中解析出用户 ID
        String userId = "123"; // 或者从 token 中解析出用户 ID

        SseEmitter emitter = new SseEmitter(-1L);
        executorService.execute(() -> {
            try {
                log.info("流式回答开始, 问题: {}", question);

                // 获取当前用户的对话历史
                List> messages = sessionHistory.getOrDefault(userId, new ArrayList<>());

                // 添加用户的新问题到对话历史
                Map userMessage = new HashMap<>();
                userMessage.put("role", "user");
                userMessage.put("content", question);

                Map systemMessage = new HashMap<>();
                systemMessage.put("role", "system");
                systemMessage.put("content", "智能助手");
                messages.add(userMessage);
                messages.add(systemMessage);

                // 调用 Deepseek API
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost request = new HttpPost(API_URL);
                    request.setHeader("Content-Type", "application/json");
                    request.setHeader("Authorization", "Bearer " + API_KEY);

                    Map requestMap = new HashMap<>();
                    requestMap.put("model", "deepseek-chat");
//                    requestMap.put("model", "deepseek-reasoner");
                    requestMap.put("messages", messages); // 包含对话历史
                    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))) {
                        StringBuilder aiResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (line.startsWith("data: ")) {
                                System.err.println(line);
                                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);
                                    aiResponse.append(content); // 收集 AI 的回复
                                }
                            }
                        }

                        // 将 AI 的回复添加到对话历史
                        Map aiMessage = new HashMap<>();
                        aiMessage.put("role", "assistant");
                        aiMessage.put("content", aiResponse.toString());
                        messages.add(aiMessage);

                        // 更新会话状态
                        sessionHistory.put(userId, messages);

                        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;
    }
}
  • 前端页面 chat.html




    
    
    DeepSeek Chat
    



    

DeepSeek Chat

    3、测试

    启动项目,访问 http://localhost:8080/deepSeek 即可出现页面,开始对话即可

    最近面试BAT,整理一份面试资料《Java面试BATJ通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。

    获取方式:关注《java架构笔记》回复 《java》 领取,更多内容陆续奉上。

    SpringBoot接入DeepSeek,保姆级教程_第3张图片

    你可能感兴趣的:(spring,boot,后端,java)