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

Spring Boot 整合AI大模型实战:手把手带你接入DeepSeek API

前言

随着AI大模型的快速普及,越来越多的Java开发者希望将AI能力集成到自己的项目中。本文手把手带你用Spring Boot接入DeepSeek API,实现一个具备AI对话能力的后端服务。

一、环境准备

  • JDK 17+
  • Spring Boot 3.x
  • Maven 3.8+
  • DeepSeek API Key(到 platform.deepseek.com 免费申请)

二、添加依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency>

三、配置 application.yml

deepseek:api-key: sk-xxxxxxxxxxxxxxxxbase-url: https://api.deepseek.commodel: deepseek-chatmax-tokens: 2048

四、创建配置类

@Configuration
@ConfigurationProperties(prefix = "deepseek")
@Data
public class DeepSeekConfig {private String apiKey;private String baseUrl;private String model;private Integer maxTokens;@Beanpublic WebClient deepSeekWebClient() {return WebClient.builder().baseUrl(baseUrl).defaultHeader("Authorization", "Bearer " + apiKey).defaultHeader("Content-Type", "application/json").build();}
}

五、定义请求/响应实体

// 请求体
@Data
public class ChatRequest {private String model;private List<Message> messages;@JsonProperty("max_tokens")private Integer maxTokens;private Boolean stream = false;@Data@AllArgsConstructorpublic static class Message {private String role;  // system / user / assistantprivate String content;}
}// 响应体
@Data
public class ChatResponse {private String id;private List<Choice> choices;@Datapublic static class Choice {private Message message;}@Datapublic static class Message {private String role;private String content;}
}

六、实现Service层

@Service
@RequiredArgsConstructor
public class DeepSeekService {private final WebClient deepSeekWebClient;private final DeepSeekConfig config;public String chat(String userMessage) {ChatRequest request = new ChatRequest();request.setModel(config.getModel());request.setMaxTokens(config.getMaxTokens());request.setMessages(List.of(new ChatRequest.Message("system", "你是一个专业Java开发助手"),new ChatRequest.Message("user", userMessage)));ChatResponse response = deepSeekWebClient.post().uri("/v1/chat/completions").bodyValue(request).retrieve().bodyToMono(ChatResponse.class).block();return response.getChoices().get(0).getMessage().getContent();}
}

七、实现Controller层

@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AiController {private final DeepSeekService deepSeekService;@PostMapping("/chat")public ResponseEntity<String> chat(@RequestBody Map<String, String> body) {String message = body.get("message");String reply = deepSeekService.chat(message);return ResponseEntity.ok(reply);}
}

八、测试

curl -X POST http://localhost:8080/api/ai/chat \-H "Content-Type: application/json" \-d '{"message": "帮我写一个Spring Boot分页查询的示例"}'

总结

通过以上步骤,我们完成了Spring Boot整合DeepSeek API的全流程。后续可以进一步扩展:

  • 支持流式输出(SSE)
  • 加入对话历史管理
  • 集成Redis缓存常用回答
  • 接入其他大模型(通义千问、文心一言等)

本文由AI辅助创作。

http://www.jsqmd.com/news/522828/

相关文章:

  • 造相 Z-Image 高效部署教程:基于insbase-cuda124-pt250-dual-v7底座
  • ofa_image-caption实战教程:添加用户反馈机制优化后续模型迭代方向
  • OpenTabletDriver在艺术创作中的应用:数字绘画最佳实践
  • BGE-M3开源模型入门指南:双编码器原理、embedding生成与向量相似度计算
  • 2026年国产智能客服系统,支持开源部署与多语言在线服务 - 品牌2026
  • 手里有2326开头沃尔玛卡别乱扔!亲测3种正规回收方式 - 猎卡回收公众号
  • 基于FnOS的虚拟云桌面实战:前端开发环境搭建与Docker优化技巧
  • 嵌入式Linux能否在无MMU处理器上运行?
  • OpenClaw终端增强:GLM-4.7-Flash解释错误命令与推荐修正
  • Prompt-to-Prompt代码架构解析:深入理解AttentionControl类设计
  • Crypto Trading Bot 交易所集成详解:Bitmex、Binance、Bybit 实战指南
  • 2026年在线客服哪家好?优质客服系统选购全攻略 - 品牌2026
  • CircleMenu 部署与发布:使用 CocoaPods 和 Carthage 的完整流程
  • 避坑!用VSCode+LaTeX Workshop配置同济大学论文模板,比TexStudio更香?
  • Monkey Patching高级技巧:处理闭包、接口和私有方法的完整方案
  • MiniCPM-V-2_6轻量视频理解:10秒短视频生成300字时空结构化描述
  • EasyAnimateV5-7b-zh-InP图生视频模型部署避坑指南:新手必看
  • Phi-4-mini-reasoning在Linux环境下的部署与优化指南
  • Java并发——CAS(比较并替换)
  • 避坑指南:Kscan暴力破解模块的正确打开方式(含自定义字典配置)
  • 告别‘幽灵机械臂’:在Ubuntu 20.04 + ROS Noetic下,用Xacro重构你的SolidWorks URDF模型
  • Qwen3-Reranker-0.6B惊艳效果:重排序使RAG在复杂嵌套Query中准确率翻倍
  • 自动化测试实践:为cv_unet_image-colorization模型服务编写全面的测试用例
  • 声音克隆黑科技!用Fish Speech 1.5上传5秒音频,克隆你的专属语音
  • 2026 年金三银四版互联网大厂 Java 面试指南
  • 基于COM接口的MATLAB与Origin自动化数据管道构建
  • 279商业模式纯解析:老板一眼看透的底层逻辑
  • 用PPO算法搞定机器人仿真参数调优:从零到一的Isaac Gym实战指南
  • 嵌入式工程师七阶能力跃迁模型与工程验证体系
  • 智能体开发避坑指南:CoreAgent平台搭建企业级AI员工的5个关键配置