DeepSeek API 调用 - Spring Boot 实现

news/2025/2/15 9:09:06/

DeepSeek API 调用 - Spring Boot 实现

1. 项目依赖

pom.xml 中添加以下依赖:

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

2. 项目结构

deepseek-project/
├── src/main/java/com/example/deepseek/
│   ├── DeepSeekApplication.java
│   ├── config/
│   │   └── DeepSeekConfig.java
│   ├── model/
│   │   ├── ChatRequest.java
│   │   ├── ChatResponse.java
│   │   └── Message.java
│   └── service/
│       └── DeepSeekService.java
└── conversation.txt

3. 完整代码实现

java_42">3.1 配置类 DeepSeekConfig.java
java">package com.example.deepseek.config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;@Configuration
@Getter
public class DeepSeekConfig {@Value("${deepseek.api.url}")private String apiUrl;@Value("${deepseek.api.key}")private String apiKey;
}
3.2 请求/响应模型

Message.java:

java">package com.example.deepseek.model;import lombok.Data;@Data
public class Message {private String role;private String content;
}

ChatRequest.java:

java">package com.example.deepseek.model;import lombok.Data;
import java.util.List;@Data
public class ChatRequest {private String model = "deepseek-ai/DeepSeek-V3";private List<Message> messages;private boolean stream = true;private int max_tokens = 2048;private double temperature = 0.7;private double top_p = 0.7;private int top_k = 50;private double frequency_penalty = 0.5;private int n = 1;private ResponseFormat response_format = new ResponseFormat("text");@Datapublic static class ResponseFormat {private String type;public ResponseFormat(String type) {this.type = type;}}
}

ChatResponse.java:

java">package com.example.deepseek.model;import lombok.Data;
import java.util.List;@Data
public class ChatResponse {private List<Choice> choices;@Datapublic static class Choice {private Delta delta;}@Datapublic static class Delta {private String content;}
}
java_130">3.3 服务类 DeepSeekService.java
java">package com.example.deepseek.service;import com.example.deepseek.config.DeepSeekConfig;
import com.example.deepseek.model.ChatRequest;
import com.example.deepseek.model.ChatResponse;
import com.example.deepseek.model.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Scanner;@Service
@RequiredArgsConstructor
public class DeepSeekService {private final DeepSeekConfig config;private final WebClient.Builder webClientBuilder;private final ObjectMapper objectMapper = new ObjectMapper();public void startInteractiveChat() {try (Scanner scanner = new Scanner(System.in);PrintWriter fileWriter = new PrintWriter(new FileWriter("conversation.txt", true))) {while (true) {System.out.print("\n请输入您的问题 (输入 q 退出): ");String question = scanner.nextLine().trim();if ("q".equalsIgnoreCase(question)) {System.out.println("程序已退出");break;}// 保存问题saveToFile(fileWriter, question, true);// 发起对话请求Flux<String> responseFlux = sendChatRequest(question);StringBuilder fullResponse = new StringBuilder();responseFlux.doOnNext(chunk -> {System.out.print(chunk);fullResponse.append(chunk);}).doOnComplete(() -> {// 保存完整回复saveToFile(fileWriter, fullResponse.toString(), false);System.out.println("\n----------------------------------------");fileWriter.println("\n----------------------------------------");fileWriter.flush();}).blockLast();}} catch (IOException e) {e.printStackTrace();}}private Flux<String> sendChatRequest(String question) {ChatRequest request = new ChatRequest();Message userMessage = new Message();userMessage.setRole("user");userMessage.setContent(question);request.setMessages(Collections.singletonList(userMessage));return webClientBuilder.build().post().uri(config.getApiUrl()).header("Authorization", "Bearer " + config.getApiKey()).header("Content-Type", "application/json").bodyValue(request).retrieve().bodyToFlux(String.class).filter(line -> line.startsWith("data: ") && !line.equals("data: [DONE]")).map(line -> {try {String jsonStr = line.substring(6);ChatResponse response = objectMapper.readValue(jsonStr, ChatResponse.class);return response.getChoices().get(0).getDelta().getContent();} catch (Exception e) {return "";}}).filter(content -> !content.isEmpty());}private void saveToFile(PrintWriter fileWriter, String content, boolean isQuestion) {String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));if (isQuestion) {fileWriter.printf("\n[%s] Question:\n%s\n\n[%s] Answer:\n", timestamp, content, timestamp);} else {fileWriter.print(content);}fileWriter.flush();}
}
java_239">3.4 主应用类 DeepSeekApplication.java
java">package com.example.deepseek;import com.example.deepseek.service.DeepSeekService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;@SpringBootApplication
public class DeepSeekApplication {public static void main(String[] args) {ConfigurableApplicationContext context = SpringApplication.run(DeepSeekApplication.class, args);DeepSeekService deepSeekService = context.getBean(DeepSeekService.class);deepSeekService.startInteractiveChat();}
}
3.5 配置文件 application.properties
deepseek.api.url=https://api.siliconflow.cn/v1/chat/completions
deepseek.api.key=YOUR_API_KEY

4. 代码详解

4.1 关键特性
  1. 使用 Spring WebFlux 的响应式编程模型
  2. 流式处理 API 响应
  3. 文件记录对话
  4. 错误处理和异常管理
4.2 主要组件
  • DeepSeekConfig: 管理 API 配置
  • DeepSeekService: 处理对话逻辑和 API 交互
  • 模型类: 定义请求和响应结构

5. 使用方法

  1. 替换 application.properties 中的 YOUR_API_KEY
  2. 运行 DeepSeekApplication
  3. 在控制台输入问题
  4. 输入 ‘q’ 退出程序
  5. 查看 conversation.txt 获取对话记录

6. 性能和可扩展性

  • 使用响应式编程提高并发性能
  • 灵活的配置管理
  • 易于扩展和定制

7. 注意事项

  • 确保正确配置 API Key
  • 处理网络异常
  • 注意内存使用

总结

Spring Boot 实现提供了一个健壮、可扩展的 DeepSeek API 调用方案,利用响应式编程提供高效的流式对话体验。

立即体验

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ


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

相关文章

Android Studio:键值对存储sharedPreferences

一、了解 SharedPreferences SharedPreferences是Android的一个轻量级存储工具&#xff0c;它采用的存储结构是Key-Value的键值对方式&#xff0c;类似于Java的Properties&#xff0c;二者都是把Key-Value的键值对保存在配置文件中。不同的是&#xff0c;Properties的文件内容形…

基础算法 高精度运算 #大数加法

文章目录 题目链接题目解读完整代码参考 题目链接 题目解读 题目描述 输入两个正整数a,b&#xff0c;输出ab的值。 输入格式 两行&#xff0c;第一行a&#xff0c;第二行b。a和b的长度均小于1000位。 输出格式 一行&#xff0c;ab的值。 完整代码 #include<bits/stdc.h&…

Java 大视界 -- 大数据伦理与法律:Java 技术在合规中的作用与挑战(87)

&#x1f496;亲爱的朋友们&#xff0c;热烈欢迎来到 青云交的博客&#xff01;能与诸位在此相逢&#xff0c;我倍感荣幸。在这飞速更迭的时代&#xff0c;我们都渴望一方心灵净土&#xff0c;而 我的博客 正是这样温暖的所在。这里为你呈上趣味与实用兼具的知识&#xff0c;也…

DeepSeekApi对接流式输出异步聊天功能:基于Spring Boot和OkHttp的SSE应用实现

实现异步聊天功能&#xff1a;基于Spring Boot和OkHttp的SSE应用 在现代Web应用程序开发中&#xff0c;实时更新的能力对于增强用户体验至关重要。本文将详细介绍如何利用Spring Boot框架结合OkHttp库实现一个简单的异步聊天服务&#xff0c;该服务能够接收用户输入并通过Serv…

原生Three.js 和 Cesium.js 案例 。 智慧城市 数字孪生常用功能列表

对于大多数的开发者来言&#xff0c;看了很多文档可能遇见不到什么有用的&#xff0c;就算有用从文档上看&#xff0c;把代码复制到自己的本地大多数也是不能用的&#xff0c;非常浪费时间和学习成本&#xff0c; 尤其是three.js &#xff0c; cesium.js 这种难度较高&#xff…

【2025深度学习系列专栏大纲:深入探索与实践深度学习】

第一部分:深度学习基础篇 第1章:深度学习概览 1.1 深度学习的历史背景与发展轨迹 1.2 深度学习与机器学习、传统人工智能的区别与联系 1.3 深度学习的核心组件与概念解析 神经网络基础 激活函数的作用与类型 损失函数与优化算法的选择 1.4 深度学习框架简介与选择建议 第2…

如何在 Visual Studio Code 中使用 DeepSeek R1 和 Cline?

让我们面对现实吧&#xff1a;像 GitHub Copilot 这样的 AI 编码助手非常棒&#xff0c;但它们的订阅费用可能会在你的钱包里烧一个洞。进入 DeepSeek R1 — 一个免费的开源语言模型&#xff0c;在推理和编码任务方面可与 GPT-4 和 Claude 3.5 相媲美。将它与 Cline 配对&#…

基于springboot 以及vue前后端分离架构的求职招聘系统设计与实现

基于springboot 以及vue前后端分离架构的求职招聘系统设计与实现 随着互联网技术的飞速发展&#xff0c;求职招聘行业也在不断发生变革。传统的求职招聘方式往往存在着信息不对称、效率低下、交易成本高等问题&#xff0c;导致企业的招聘成本增加&#xff0c;求职者的体验下降…