SpringAI集成DeepSeek实战

news/2025/2/19 0:21:17/

DeepSeek_0">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 {@Beanpublic DeepSeekAiProperties deepSeekAiProperties() {// 配置DeepSeek属性DeepSeekAiProperties properties = new DeepSeekAiProperties();properties.setApiKey("your-api-key-here");properties.setModel("deepseek-chat"); // 设置使用的模型return properties;}@Beanpublic 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));}// 创建带有历史记录的promptPrompt 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 {@Autowiredprivate 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密钥的安全存储
  • 请求限流和错误重试
  • 响应超时处理
  • 模型参数优化
  • 成本控制

http://www.ppmy.cn/news/1572422.html

相关文章

5. Docker 本地镜像发布到阿里云

5. Docker 本地镜像发布到阿里云 文章目录 5. Docker 本地镜像发布到阿里云1. 本地镜像发布到阿里云流程最后&#xff1a; 1. 本地镜像发布到阿里云流程 镜像的生成方法&#xff1a; 基于当前容器创建一个新的镜像&#xff0c;新功能增强 docker commit [OPTIONS] 容器ID [REP…

使用docker compose启动postgres并设置时区

设置PostGres时区 方法 1: 使用 POSTGRES_INITDB_ARGS 设置时区方法 2: 使用初始化脚本设置时区创建 init-user-db.sql更新 docker-compose.yml 启动服务 要在启动 PostgreSQL 数据库时设置时区&#xff0c;可以通过在 docker-compose.yml 文件中添加环境变量或通过配置文件来实…

独立站赋能反向海淘:跨境代购系统的用户体验与支付解决方案

随着全球化的推进以及消费者对海外商品多样化需求的增长&#xff0c;独立站赋能的反向海淘模式愈发火热&#xff0c;其中跨境代购系统的用户体验与支付解决方案起着关键作用。 一、跨境代购系统的用户体验 界面友好性 独立站的页面设计需要简洁、直观&#xff0c;方便用户快速…

【Maven】多module项目优雅的实现pom依赖管理

【Maven】多module项目优雅的实现pom依赖管理 【一】方案设计原则【二】项目结构示例【三】实现思路【1】可能的问题点&#xff1a;【2】解决方案的思路&#xff1a;【3】需要注意的地方&#xff1a;【4】可能的错误&#xff1a; 【四】实现案例【1】父POM设计&#xff08;pare…

格式工厂 FormatFactory v5.18.便携版 ——多功能媒体文件转换工具

格式工厂 FormatFactory v5.18.便携版 ——多功能媒体文件转换工具 功能&#xff1a;视频 音频 图片 文档PDF格式 各种转换&#xff0c;同格式调整压缩比例&#xff0c;调整大小 特色&#xff1a;果风图标 好看; 支持多任务队列&#xff0c;完成自动关机 下载地址&#xff1…

渗透测试--文件包含漏洞

文件包含漏洞 前言 《Web安全实战》系列集合了WEB类常见的各种漏洞&#xff0c;笔者根据自己在Web安全领域中学习和工作的经验&#xff0c;对漏洞原理和漏洞利用面进行了总结分析&#xff0c;致力于漏洞准确性、丰富性&#xff0c;希望对WEB安全工作者、WEB安全学习者能有所帮助…

redis底层数据结构——整数集合

文章目录 定义内部实现升级升级的好处提升灵活性节约内存 降级总结 定义 整数集合&#xff08;intset&#xff09;是集合键的底层实现之一&#xff0c;当一个集合只包含整数值元素&#xff0c;并且这个集合的元素数量不多时&#xff0c;Redis就会使用整数集合作为集合键的底层…

singleTaskAndroid的Activity启动模式知识点总结

一. 前提知识 1.1. 任务栈知识 二. Activity启动模式的学习 2.1 standard 2.2 singleTop 2.3.singleTask 2.4.singleInstance 引言&#xff1a; Activity作为四大组件之一&#xff0c;也可以说Activity是其中最重要的一个组件&#xff0c;其负责调节APP的视图&#xff…