当前位置: 首页 > news >正文

SpringAI集成DeepSeek实战

SpringAI集成DeepSeek实战教程

引言
Spring AI作为Spring生态系统中的新成员,为开发者提供了便捷的AI集成方案。本文将详细介绍如何在Spring项目中集成DeepSeek模型,实现智能对话等功能。

环境准备
在开始之前,请确保您的开发环境满足以下要求:

  • JDK 17或更高版本
  • Spring Boot 3.x
  • Maven或Gradle构建工具
  • DeepSeek API密钥

项目配置
首先,在pom.xml中添加Spring AI的依赖:

<dependencies>
    <!-- Spring AI 核心依赖 -->
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-core</artifactId>
        <version>0.8.0</version>
    </dependency>
    
    <!-- DeepSeek 集成依赖 -->
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-deepseek</artifactId>
        <version>0.8.0</version>
    </dependency>
</dependencies>

基础配置类
创建DeepSeek配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ai.deepseek.DeepSeekAiClient;
import org.springframework.ai.deepseek.DeepSeekAiProperties;

@Configuration
public class DeepSeekConfig {
    
    @Bean
    public DeepSeekAiProperties deepSeekAiProperties() {
        // 配置DeepSeek属性
        DeepSeekAiProperties properties = new DeepSeekAiProperties();
        properties.setApiKey("your-api-key-here");
        properties.setModel("deepseek-chat"); // 设置使用的模型
        return properties;
    }
    
    @Bean
    public DeepSeekAiClient deepSeekAiClient(DeepSeekAiProperties properties) {
        // 创建DeepSeek客户端实例
        return new DeepSeekAiClient(properties);
    }
}

服务层实现
创建一个服务类来处理与DeepSeek的交互:

import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.stereotype.Service;

@Service
public class ChatService {
    
    private final DeepSeekAiClient aiClient;
    
    public ChatService(DeepSeekAiClient aiClient) {
        this.aiClient = aiClient;
    }
    
    /**
     * 发送单轮对话请求
     * @param message 用户输入的消息
     * @return AI的响应内容
     */
    public String sendMessage(String message) {
        // 创建用户消息
        UserMessage userMessage = new UserMessage(message);
        // 创建prompt对象
        Prompt prompt = new Prompt(userMessage);
        // 获取AI响应
        ChatResponse response = aiClient.generate(prompt);
        return response.getGeneration().getContent();
    }
    
    /**
     * 发送多轮对话请求
     * @param messages 对话历史记录
     * @return AI的响应内容
     */
    public String sendConversation(List<String> messages) {
        List<Message> conversationHistory = new ArrayList<>();
        
        // 构建对话历史
        for (String message : messages) {
            conversationHistory.add(new UserMessage(message));
        }
        
        // 创建带有历史记录的prompt
        Prompt prompt = new Prompt(conversationHistory);
        ChatResponse response = aiClient.generate(prompt);
        return response.getGeneration().getContent();
    }
}

控制器实现
创建REST API接口:

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/chat")
public class ChatController {
    
    private final ChatService chatService;
    
    public ChatController(ChatService chatService) {
        this.chatService = chatService;
    }
    
    /**
     * 处理单条消息请求
     * @param message 用户消息
     * @return AI响应
     */
    @PostMapping("/message")
    public ResponseEntity<String> handleMessage(@RequestBody String message) {
        try {
            String response = chatService.sendMessage(message);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("处理消息时发生错误:" + e.getMessage());
        }
    }
    
    /**
     * 处理多轮对话请求
     * @param messages 对话历史
     * @return AI响应
     */
    @PostMapping("/conversation")
    public ResponseEntity<String> handleConversation(@RequestBody List<String> messages) {
        try {
            String response = chatService.sendConversation(messages);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("处理对话时发生错误:" + e.getMessage());
        }
    }
}

异常处理
添加全局异常处理:

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理DeepSeek API相关异常
     */
    @ExceptionHandler(DeepSeekApiException.class)
    public ResponseEntity<String> handleDeepSeekApiException(DeepSeekApiException e) {
        // 记录错误日志
        log.error("DeepSeek API错误", e);
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
            .body("AI服务暂时不可用,请稍后重试");
    }
    
    /**
     * 处理其他未预期的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneralException(Exception e) {
        log.error("系统错误", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body("系统发生错误,请联系管理员");
    }
}

使用示例
以下是一个简单的使用示例:

@SpringBootApplication
public class DeepSeekDemoApplication {
    
    @Autowired
    private ChatService chatService;
    
    public void demonstrateChat() {
        // 发送单条消息
        String response1 = chatService.sendMessage("你好,请介绍一下自己");
        System.out.println("AI响应:" + response1);
        
        // 发送多轮对话
        List<String> conversation = Arrays.asList(
            "你好,我想学习Java",
            "请推荐一些好的学习资源",
            "这些资源适合初学者吗?"
        );
        String response2 = chatService.sendConversation(conversation);
        System.out.println("AI响应:" + response2);
    }
    
    public static void main(String[] args) {
        SpringApplication.run(DeepSeekDemoApplication.class, args);
    }
}

总结

通过本文的介绍,我们详细讲解了如何在Spring项目中集成DeepSeek AI服务。从基础配置到具体实现,再到异常处理,覆盖了实际开发中的主要场景。通过使用Spring AI提供的抽象层,我们可以更加便捷地集成和使用AI能力,而不需要直接处理底层的API调用细节。

需要注意的是,在实际开发中,还需要考虑以下几点:

  • API密钥的安全存储
  • 请求限流和错误重试
  • 响应超时处理
  • 模型参数优化
  • 成本控制

相关文章:

  • 【Linux网络-网络基础】计算机网络背景+协议+OSI七层模型
  • 解释 Git 的基本概念和使用方式。
  • 渗透利器:Burp Suite 联动 XRAY 图形化工具.(主动扫描+被动扫描)
  • 2025前端面试题超全面解析(附答案与深度扩展)
  • PicoShare实操:轻松实现远程文件共享无需公网IP与云服务器
  • 大数据学习之SparkStreaming、PB级百战出行网约车项目一
  • 华纳云:如何从服务器日志中发现僵尸进程?
  • UGUI Canvas为Overlay模式下的UI元素的position和localPosition
  • 2月14日笔记
  • 安装OpenJDK21(linux、macos)
  • 站群服务器和普通服务器有哪些不同之处?
  • 【分布式理论9】分布式协同:分布式系统进程互斥与互斥算法
  • 软著申请(一)实名认证【2025年最新版】
  • 在本地校验密码或弱口令 (windows)
  • 汽车 OTA 升级:提升下载与升级速度,优化用户体验
  • iOS主要知识点梳理回顾-4-运行时类和实例的操作
  • MAC 系统关屏幕后电量消耗极快 Wake Requests
  • 服务器中部署大模型DeepSeek-R1 | 本地部署DeepSeek-R1大模型 | deepseek-r1部署详细教程
  • Win10环境借助DockerDesktop部署Open web UI集成DeepSeek
  • 【二叉树学习7】
  • 中铁房地产24.7亿元竞得上海松江新城宅地,溢价率20.42%
  • 一周文化讲座|城市移民与数字时代的新工作
  • 读图|展现城市品格,上海城市影像走进南美
  • 进化版大巴黎通杀英超,那个男人后悔了吗
  • 泉州一家婚介机构广告牌越南新娘七天闪婚领证?市监部门介入
  • 以军总参谋长:已进入“决定性打击计划的第二阶段”