基于SpringAI+DeepSeek實現(xiàn)流式對話功能
引言
前面一篇文章我們實現(xiàn)了《Spring AI內置DeepSeek的詳細步驟》,但是大模型的響應速度通常是很慢的,為了避免用戶用戶能夠耐心等待輸出的結果,我們通常會使用流式輸出一點點將結果輸出給用戶。
那么問題來了,想要實現(xiàn)流式結果輸出,后端和前端要如何配合?后端要使用什么技術實現(xiàn)流式輸出呢?接下來本文給出具體的實現(xiàn)代碼,先看最終實現(xiàn)效果:

解決方案
在 Spring Boot 中實現(xiàn)流式輸出可以使用 Sse(Server-Sent Events,服務器發(fā)送事件)技術來實現(xiàn),它是一種服務器推送技術,適合單向實時數(shù)據流,我們使用 Spring MVC(基于 Servlet)中的 SseEmitter 對象來實現(xiàn)流式輸出。
具體實現(xiàn)如下。
1.后端代碼
Spring Boot 程序使用 SseEmitter 對象提供的 send 方法發(fā)送數(shù)據,具體實現(xiàn)代碼如下:
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@RestController
public class StreamController {
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter streamData() {
// 創(chuàng)建 SSE 發(fā)射器,設置超時時間(例如 1 分鐘)
SseEmitter emitter = new SseEmitter(60_000L);
// 創(chuàng)建新線程,防止主程序阻塞
new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
Thread.sleep(1000); // 模擬延遲
// 發(fā)送數(shù)據
emitter.send("time=" + System.currentTimeMillis());
}
// 發(fā)送完畢
emitter.complete();
} catch (Exception e) {
emitter.completeWithError(e);
}
}).start();
return emitter;
}
}
2.前端代碼
前端接受數(shù)據流也比較簡單,不需要在使用傳統(tǒng) Ajax 技術了,只需要創(chuàng)建一個 EventSource 對象,監(jiān)聽后端 SSE 接口,然后將接收到的數(shù)據流展示出來即可,如下代碼所示:
<!DOCTYPE html>
<html>
<head>
<title>流式輸出示例</title>
</head>
<body>
<h2>流式數(shù)據接收演示</h2>
<button onclick="startStream()">開始接收數(shù)據</button>
<div id="output" style="margin-top: 20px; border: 1px solid #ccc; padding: 10px;"></div>
<script>
function startStream() {
const output = document.getElementById('output');
output.innerHTML = ''; // 清空之前的內容
const eventSource = new EventSource('/stream');
eventSource.onmessage = function(e) {
const newElement = document.createElement('div');
newElement.textContent = "print -> " + e.data;
output.appendChild(newElement);
};
eventSource.onerror = function(e) {
console.error('EventSource 錯誤:', e);
eventSource.close();
const newElement = document.createElement('div');
newElement.textContent = "連接關閉";
output.appendChild(newElement);
};
}
</script>
</body>
</html>
3.運行項目
運行項目測試結果:
- 啟動 Spring Boot 項目。
- 在瀏覽器中訪問地址 http://localhost:8080/index.html,即可看到流式輸出的內容逐漸顯示在頁面上。
4.最終版:流式輸出
后端代碼如下:
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.util.Map;
@RestController
public class ChatController {
private final OpenAiChatModel chatModel;
@Autowired
public ChatController(OpenAiChatModel chatModel) {
this.chatModel = chatModel;
}
@GetMapping("/ai/generate")
public Map generate(@RequestParam(value = "message", defaultValue = "你是誰?") String message) {
return Map.of("generation", this.chatModel.call(message));
}
@GetMapping("/ai/generateStream")
public SseEmitter streamChat(@RequestParam String message) {
// 創(chuàng)建 SSE 發(fā)射器,設置超時時間(例如 1 分鐘)
SseEmitter emitter = new SseEmitter(60_000L);
// 創(chuàng)建 Prompt 對象
Prompt prompt = new Prompt(new UserMessage(message));
// 訂閱流式響應
chatModel.stream(prompt).subscribe(response -> {
try {
String content = response.getResult().getOutput().getContent();
System.out.print(content);
// 發(fā)送 SSE 事件
emitter.send(SseEmitter.event()
.data(content)
.id(String.valueOf(System.currentTimeMillis()))
.build());
} catch (Exception e) {
emitter.completeWithError(e);
}
},
error -> { // 異常處理
emitter.completeWithError(error);
},
() -> { // 完成處理
emitter.complete();
}
);
// 處理客戶端斷開連接
emitter.onCompletion(() -> {
// 可在此處釋放資源
System.out.println("SSE connection completed");
});
emitter.onTimeout(() -> {
emitter.complete();
System.out.println("SSE connection timed out");
});
return emitter;
}
}
前端核心 JS 代碼如下:
$('#send-button').click(function () {
const message = $('#chat-input').val();
const eventSource = new EventSource(`/ai/generateStream?message=` + message);
// 構建動態(tài)結果
var chatMessages = $('#chat-messages');
var newMessage = $('<div class="message user"></div>');
newMessage.append('<img class="avatar" src="/imgs/user.png" alt="用戶頭像">');
newMessage.append(`<span class="nickname">${message}</span>`);
chatMessages.prepend(newMessage);
var botMessage = $('<div class="message bot"></div>');
botMessage.append('<img class="avatar" src="/imgs/robot.png" alt="助手頭像">');
// 流式輸出
eventSource.onmessage = function (event) {
botMessage.append(`${event.data}`);
};
chatMessages.prepend(botMessage);
$('#chat-input').val('');
eventSource.onerror = function (err) {
console.error("EventSource failed:", err);
eventSource.close();
};
});
以上代碼中的“$”代表的是 jQuery。
到此這篇關于基于Spring AI+DeepSeek實現(xiàn)流式對話功能的文章就介紹到這了,更多相關Spring AI DeepSeek流式對話內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解析SpringBoot @EnableAutoConfiguration的使用
這篇文章主要介紹了解析SpringBoot @EnableAutoConfiguration的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09
springboot+zookeeper實現(xiàn)分布式鎖的示例代碼
本文主要介紹了springboot+zookeeper實現(xiàn)分布式鎖的示例代碼,文中根據實例編碼詳細介紹的十分詳盡,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
Java使用DFA算法實現(xiàn)過濾多家公司自定義敏感字功能詳解
這篇文章主要介紹了Java使用DFA算法實現(xiàn)過濾多家公司自定義敏感字功能,結合實例形式分析了DFA算法的實現(xiàn)原理及過濾敏感字的相關操作技巧,需要的朋友可以參考下2017-08-08
springboot配置多數(shù)據源的一款框架(dynamic-datasource-spring-boot-starter
dynamic-datasource-spring-boot-starter 是一個基于 springboot 的快速集成多數(shù)據源的啟動器,今天通過本文給大家分享這款框架配置springboot多數(shù)據源的方法,一起看看吧2021-09-09
SpringBoot中的@EnableConfigurationProperties注解詳細解析
這篇文章主要介紹了SpringBoot中的@EnableConfigurationProperties注解詳細解析,如果一個配置類只配置@ConfigurationProperties注解,而沒有使用@Component或者實現(xiàn)了@Component的其他注解,那么在IOC容器中是獲取不到properties 配置文件轉化的bean,需要的朋友可以參考下2024-01-01

