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

java springboot deepseek流式对话集成示例

1.直接上代码-后端:

@RestController
@CrossOrigin(origins = "*")
public class DeepSeekController {private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";private final ObjectMapper objectMapper = new ObjectMapper();@GetMapping(value = "/stream", produces = "text/event-stream")public SseEmitter streamChat(@RequestParam String message) {SseEmitter emitter = new SseEmitter(60_000L); // 超时60秒OkHttpClient client = new OkHttpClient.Builder().connectTimeout(200, TimeUnit.SECONDS)  // 连接超时.readTimeout(200, TimeUnit.SECONDS)    // 读取超时(需大于流式响应生成时间).build();String jsonBody = buildRequestJson(message); // 构建请求体Request request = new Request.Builder().url(API_URL).header("Authorization", "XXXXXXX").post(RequestBody.create(jsonBody, MediaType.get("application/json"))).build();client.newCall(request).enqueue(new Callback() {@Overridepublic void onResponse(Call call, Response response) throws IOException {try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body().byteStream()))) {String line;while ((line = reader.readLine()) != null) {if (line.startsWith("data: ")) {String content = parseContent(line.substring(6));emitter.send(SseEmitter.event().data(content));}}emitter.complete();}}@Overridepublic void onFailure(Call call, IOException e) {emitter.completeWithError(e);}});return emitter;}// 安全解析JSON内容private String parseContent(String jsonLine) {try {System.out.println(jsonLine);JsonNode node = objectMapper.readTree(jsonLine);return node.path("choices").get(0).path("delta").path("content").asText();} catch (Exception e) {return "[解析错误]";}}// 构建请求体private String buildRequestJson(String message) {return String.format("{\"model\":\"deepseek-chat\",\"stream\":true,\"messages\":[{\"role\":\"user\",\"content\":\"%s\"}]}",message.replace("\"", "\\\""));}
}
        <!-- OkHttp用于SSE通信 --><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.10.0</version></dependency><!-- JSON处理 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.10.3</version></dependency>

2.前端

<!DOCTYPE html>
<meta charset="UTF-8"/>
<html>
<head><title>DeepSeek流式对话</title><link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.9.96/css/materialdesignicons.min.css" rel="stylesheet"><style>/* 样式见下方CSS部分 */.chat-container {max-width: 800px;margin: 20px auto;background: #F9FAFB;border-radius: 12px;box-shadow: 0 8px 30px rgba(0,0,0,0.1);}.chat-messages {height: 70vh;padding: 20px;overflow-y: auto;}.message {margin: 12px 0;padding: 14px 20px;border-radius: 12px;max-width: 80%;animation: fadeIn 0.3s ease;}.user-message {background: #E3F2FD;margin-left: auto;border-bottom-right-radius: 4px;}.ai-message {background: #FFFFFF;box-shadow: 0 2px 8px rgba(0,0,0,0.05);border-bottom-left-radius: 4px;}@keyframes fadeIn {from { opacity: 0; transform: translateY(10px); }to { opacity: 1; transform: translateY(0); }}</style>
</head>
<body>
<div class="chat-container"><div class="chat-messages" id="chatMessages"><!-- 消息动态插入 --></div><div class="input-area"><input type="text" id="inputField" placeholder="输入您的问题..."><button id="sendBtn"><i class="mdi mdi-send"></i></button></div>
</div>
<script>// 脚本见下方JS部分document.getElementById('sendBtn').addEventListener('click', () => {const input = document.getElementById('inputField').value.trim();if (!input) return;// 清空输入框document.getElementById('inputField').value = '';// 显示用户消息appendMessage(input, 'user');// 创建AI消息容器const aiMessageDiv = appendMessage('', 'ai');// 建立SSE连接const eventSource = new EventSource(`/stream?message=${encodeURIComponent(input)}`);eventSource.onmessage = (e) => {aiMessageDiv.textContent += e.data;aiMessageDiv.scrollIntoView({ behavior: 'smooth' });};eventSource.onerror = () => {eventSource.close();aiMessageDiv.textContent += '(对话结束)';};});function appendMessage(content, type) {const container = document.getElementById('chatMessages');const div = document.createElement('div');div.className = `message ${type}-message`;div.textContent = content;container.appendChild(div);return div;}</script>
</body>
</html>
http://www.xdnf.cn/news/297919.html

相关文章:

  • UE5 材质淡入淡出
  • 【数据结构】求有向图强连通分量的方法
  • 【开发工具】Window安装WSL及配置Vscode获得Linux开发环境
  • 虚拟现实视频播放器 2.6.1 | 支持多种VR格式,提供沉浸式观看体验的媒体播放器
  • Spark,HDFS客户端操作
  • mysql中select 1 from的作用
  • 博客系统测试报告
  • 在命令行终端中快速打开npm包官网
  • MySQL从入门到精通(二):Windows和Mac版本MySQL安装教程
  • 【STM32项目实战】一文了解单片机的SPI驱动外设功能
  • (十)深入了解AVFoundation-采集:录制视频功能的实现
  • HTTP 与 HTTPS 的深度剖析:差异、原理与应用场景
  • Day17 聚类算法(K-Means、DBSCAN、层次聚类)
  • MacOS+VSCODE 安装esp-adf详细流程
  • Three.js和WebGL区别、应用建议
  • 【奔跑吧!Linux 内核(第二版)】第1章:Linux 系统基础知识
  • 【测试开发】概念篇 - 从理解需求到认识常见开发、测试模型
  • 第二节:Vben Admin 最新 v5.0 对接后端登录接口(上)
  • 用OMS从MySQL迁移到OceanBase,字符集utf8与utf8mb4的差异
  • 如何保障服务器租用中的数据安全?
  • 基于 Trae 的单细胞 RNA 测序分析与可视化
  • Linux下的好玩的命令
  • Linux:进程间通信---命名管道共享内存
  • Android组件化 -> Debug模式下,本地构建module模块的AAR和APK
  • Nginx安全防护与HTTPS部署
  • 如何搭建spark yarn模式集群的集群
  • OpenKylin安装Elastic Search8
  • 多线程“CPU 飙高”问题:如何确保配置的线程数与CPU核数匹配(Java、GoLang、Python )中的最佳实践解决方案
  • 数据分析指标体系
  • 深度剖析:可视化如何重塑驾驶舱信息交互模式