SpringAI+DeepSeek實(shí)現(xiàn)流式對(duì)話!
那么問(wèn)題來(lái)了,想要實(shí)現(xiàn)流式結(jié)果輸出,后端和前端要如何配合?后端要使用什么技術(shù)實(shí)現(xiàn)流式輸出呢?接下來(lái)本文給出具體的實(shí)現(xiàn)代碼,先看最終實(shí)現(xiàn)效果:
圖片
解決方案
在 Spring Boot 中實(shí)現(xiàn)流式輸出可以使用 Sse(Server-Sent Events,服務(wù)器發(fā)送事件)技術(shù)來(lái)實(shí)現(xiàn),它是一種服務(wù)器推送技術(shù),適合單向?qū)崟r(shí)數(shù)據(jù)流,我們使用 Spring MVC(基于 Servlet)中的 SseEmitter 對(duì)象來(lái)實(shí)現(xiàn)流式輸出。
具體實(shí)現(xiàn)如下。
1.后端代碼
Spring Boot 程序使用 SseEmitter 對(duì)象提供的 send 方法發(fā)送數(shù)據(jù),具體實(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ā)射器,設(shè)置超時(shí)時(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ù)流也比較簡(jiǎn)單,不需要在使用傳統(tǒng) Ajax 技術(shù)了,只需要?jiǎng)?chuàng)建一個(gè) EventSource 對(duì)象,監(jiān)聽(tīng)后端 SSE 接口,然后將接收到的數(shù)據(jù)流展示出來(lái)即可,如下代碼所示:
<!DOCTYPE html>
<html>
<head>
<title>流式輸出示例</title>
</head>
<body>
<h2>流式數(shù)據(jù)接收演示</h2>
<button onclick="startStream()">開(kāi)始接收數(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 錯(cuò)誤:', e);
eventSource.close();
const newElement = document.createElement('div');
newElement.textContent = "連接關(guān)閉";
output.appendChild(newElement);
};
}
</script>
</body>
</html>
3.運(yùn)行項(xiàng)目
運(yùn)行項(xiàng)目測(cè)試結(jié)果:
- 啟動(dòng) Spring Boot 項(xiàng)目。
- 在瀏覽器中訪問(wèn)地址 http://localhost:8080/index.html,即可看到流式輸出的內(nèi)容逐漸顯示在頁(yè)面上。
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 = "你是誰(shuí)?") String message) {
return Map.of("generation", this.chatModel.call(message));
}
@GetMapping("/ai/generateStream")
public SseEmitter streamChat(@RequestParam String message) {
// 創(chuàng)建 SSE 發(fā)射器,設(shè)置超時(shí)時(shí)間(例如 1 分鐘)
SseEmitter emitter = new SseEmitter(60_000L);
// 創(chuàng)建 Prompt 對(duì)象
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();
}
);
// 處理客戶端斷開(kāi)連接
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)建動(dòng)態(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。