Spring Boot 整合AI大模型实战:手把手带你接入DeepSeek API
<h2>前言</h2><p>随着AI大模型的快速普及,越来越多的Java开发者希望将AI能力集成到自己的项目中。本文手把手带你用Spring Boot接入DeepSeek API,实现一个具备AI对话能力的后端服务。</p>
<h2>一、环境准备</h2>
<ul>
<li>JDK 17+</li>
<li>Spring Boot 3.x</li>
<li>Maven 3.8+</li>
<li>DeepSeek API Key(到 platform.deepseek.com 免费申请)</li>
</ul>
<h2>二、添加依赖</h2>
<pre><code><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></code></pre>
<h2>三、配置 application.yml</h2>
<pre><code>deepseek:
api-key: sk-xxxxxxxxxxxxxxxx
base-url: https://api.deepseek.com
model: deepseek-chat
max-tokens: 2048</code></pre>
<h2>四、创建配置类</h2>
<pre><code>@Configuration
@ConfigurationProperties(prefix = "deepseek")
@Data
public class DeepSeekConfig {
private String apiKey;
private String baseUrl;
private String model;
private Integer maxTokens;
@Bean
public WebClient deepSeekWebClient() {
return WebClient.builder()
.baseUrl(baseUrl)
.defaultHeader("Authorization", "Bearer " + apiKey)
.defaultHeader("Content-Type", "application/json")
.build();
}
}</code></pre>
<h2>五、定义请求/响应实体</h2>
<pre><code>// 请求体
@Data
public class ChatRequest {
private String model;
private List<Message> messages;
@JsonProperty("max_tokens")
private Integer maxTokens;
private Boolean stream = false;
@Data
@AllArgsConstructor
public static class Message {
private String role;// system / user / assistant
private String content;
}
}
// 响应体
@Data
public class ChatResponse {
private String id;
private List<Choice> choices;
@Data
public static class Choice {
private Message message;
}
@Data
public static class Message {
private String role;
private String content;
}
}</code></pre>
<h2>六、实现Service层</h2>
<pre><code>@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();
}
}</code></pre>
<h2>七、实现Controller层</h2>
<pre><code>@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);
}
}</code></pre>
<h2>八、测试</h2>
<pre><code>curl -X POST http://localhost:8080/api/ai/chat \
-H "Content-Type: application/json" \
-d '{"message": "帮我写一个Spring Boot分页查询的示例"}'</code></pre>
<h2>总结</h2>
<p>通过以上步骤,我们完成了Spring Boot整合DeepSeek API的全流程。后续可以进一步扩展:</p>
<ul>
<li>支持流式输出(SSE)</li>
<li>加入对话历史管理</li>
<li>集成Redis缓存常用回答</li>
<li>接入其他大模型(通义千问、文心一言等)</li>
</ul>
<p><em>本文由AI辅助创作。</em></p>
</div>
<div id="MySignature" role="contentinfo">
---
📌 **如果觉得文章对你有帮助,欢迎点赞👍收藏⭐!**
💬 有问题或建议?欢迎在评论区留言讨论~
🔗 更多技术干货请关注作者:弥烟袅绕
📚 本文地址:https://www.cnblogs.com/czlws/p/19757373<br><br>
来源:https://www.cnblogs.com/czlws/p/19757373
頁:
[1]