DeepSeek+SpringAI實現(xiàn)流式對話!
前一篇文章我們實現(xiàn)了《SpringAI集成滿血版DeepSeek》,但是大模型的響應(yīng)速度通常是很慢的,為了避免用戶用戶能夠耐心等待輸出的結(jié)果,我們通常會使用流式輸出一點點將結(jié)果輸出給用戶。
那么問題來了,想要實現(xiàn)流式結(jié)果輸出,后端和前端要如何配合?后端要使用什么技術(shù)實現(xiàn)流式輸出呢?接下來本文給出具體的實現(xiàn)代碼,先看最終實現(xiàn)效果:
解決方案
在 Spring Boot 中實現(xiàn)流式輸出可以使用 Sse(Server-Sent Events,服務(wù)器發(fā)送事件)技術(shù)來實現(xiàn),它是一種服務(wù)器推送技術(shù),適合單向?qū)崟r數(shù)據(jù)流,我們使用 Spring MVC(基于 Servlet)中的 SseEmitter 對象來實現(xiàn)流式輸出。
具體實現(xiàn)如下。
1.后端代碼
Spring Boot 程序使用 SseEmitter 對象提供的 send 方法發(fā)送數(shù)據(jù),具體實現(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ā)射器,設(shè)置超時時間(例如 1 分鐘)
SseEmitter emitter = new SseEmitter(60_000L);
// 創(chuàng)建新線程,防止主程序阻塞
new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
Thread.sleep(1000); // 模擬延遲
// 發(fā)送數(shù)據(jù)
emitter.send("time=" + System.currentTimeMillis());
}
// 發(fā)送完畢
emitter.complete();
} catch (Exception e) {
emitter.completeWithError(e);
}
}).start();
return emitter;
}
}
2.前端代碼
前端接受數(shù)據(jù)流也比較簡單,不需要在使用傳統(tǒng) Ajax 技術(shù)了,只需要創(chuàng)建一個 EventSource 對象,監(jiān)聽后端 SSE 接口,然后將接收到的數(shù)據(jù)流展示出來即可,如下代碼所示:
<!DOCTYPE html>
<html>
<head>
<title>流式輸出示例</title>
</head>
<body>
<h2>流式數(shù)據(jù)接收演示</h2>
<button onclick="startStream()">開始接收數(shù)據(jù)</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 = ''; // 清空之前的內(nèi)容
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 = "連接關(guān)閉";
output.appendChild(newElement);
};
}
</script>
</body>
</html>
3.運行項目
運行項目測試結(jié)果:
- 啟動 Spring Boot 項目。
- 在瀏覽器中訪問地址 http://localhost:8080/index.html,即可看到流式輸出的內(nèi)容逐漸顯示在頁面上。
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ā)射器,設(shè)置超時時間(例如 1 分鐘)
SseEmitter emitter = new SseEmitter(60_000L);
// 創(chuàng)建 Prompt 對象
Prompt prompt = new Prompt(new UserMessage(message));
// 訂閱流式響應(yīng)
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);
// 構(gòu)建動態(tài)結(jié)果
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。