当前位置: 首页 > 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>

相关文章:

  • 推荐系统架构设计
  • 计算机网络复习资料
  • 内存管理(C++)
  • Polygon Miden网络:具有客户端执行的边缘区块链
  • IBM BAW(原BPM升级版)使用教程:基本概念
  • Houdini制作烟雾消散并导入UE5
  • 数字孪生储能充电站,实现智慧能源设施全景管控
  • JDK 发展历史及其版本特性
  • Python训练打卡Day17
  • 基于 AI 的工程投标六随机五区间报价得分模型模拟计算
  • 云计算与大数据进阶 | 25、可扩展系统构建
  • 力扣面试150题--对称二叉树
  • 【大模型面试每日一题】Day 10:混合精度训练如何加速大模型训练?可能出现什么问题?如何解决?
  • MYSQL的DDL语言和单表查询
  • LearnOpenGL---绘制三角形
  • 多线程网络编程:粘包问题、多线程/多进程服务器实战与常见问题解析
  • 【实战项目】简易版的 QQ 音乐:一
  • 文件上传/读取/包含漏洞技术说明
  • 大模型——GraphRAG基于知识图谱+大模型技术构建的AI知识库系统
  • 第1.3讲、什么是 Attention?——从点菜说起 [特殊字符]️
  • 专访|“甲亢哥”的操盘手,带NBA球星们玩转中国流量
  • 李云泽:将尽快推出支持小微企业民营企业融资一揽子政策
  • 退休11年后,71岁四川厅官杨家卷被查
  • 马斯克的胜利?OpenAI迫于压力放弃营利性转型计划
  • 马上评|子宫肌瘤惊现男性患者,如此论文何以一路绿灯?
  • 抗战回望18︱《广西学生军》:“广西的政治基础是青年”