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

DeepSeek+SpringAI完成流式对话

大模型的响应速度通常是很慢的,为了避免用户用户能够耐心等待输出的结果,我们通常会使用流式输出一点点将结果输出给用户。

那么问题来了,想要实现流式结果输出,后端和前端要如何配合?后端要使用什么技术实现流式输出呢?接下来本文给出具体的实现代码,先看最终实现效果:
在这里插入图片描述

解决方案
在 Spring Boot 中实现流式输出可以使用 Sse(Server-Sent Events,服务器发送事件)技术来实现,它是一种服务器推送技术,适合单向实时数据流,我们使用 Spring MVC(基于 Servlet)中的 SseEmitter 对象来实现流式输出。

具体实现如下。
1.后端代码
Spring Boot 程序使用 SseEmitter 对象提供的 send 方法发送数据,具体实现代码如下:

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(
) {
// 创建 SSE 发射器,设置超时时间(例如 1 分钟)
SseEmitter emitter =
new SseEmitter(60_000L
)
;
// 创建新线程,防止主程序阻塞
new Thread((
) ->
{
try {
for (
int i = 1
; i <= 5
; i++
) {
Thread.sleep(1000
)
;
// 模拟延迟
// 发送数据
emitter.send("time=" + System.currentTimeMillis(
)
)
;
}
// 发送完毕
emitter.complete(
)
;
}
catch (Exception e) {
emitter.completeWithError(e)
;
}
}
).start(
)
;
return emitter;
}
}

2.前端代码
前端接受数据流也比较简单,不需要在使用传统 Ajax 技术了,只需要创建一个 EventSource 对象,监听后端 SSE 接口,然后将接收到的数据流展示出来即可,如下代码所示:

<
!DOCTYPE html>
<html><head><title>流式输出示例</title></head><body><h2>流式数据接收演示</h2><button onclick="startStream()">开始接收数据</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) {
// 创建 SSE 发射器,设置超时时间(例如 1 分钟)
SseEmitter emitter =
new SseEmitter(60_000L
)
;
// 创建 Prompt 对象
Prompt prompt =
new Prompt(
new UserMessage(message)
)
;
// 订阅流式响应
chatModel.stream(prompt).subscribe(response ->
{
try {
String content = response.getResult(
).getOutput(
).getContent(
)
;
System.out.print(content)
;
// 发送 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)
;
// 构建动态结果
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();};});
http://www.jsqmd.com/news/10058/

相关文章:

  • Rocky9系统Grub修复实验
  • 2025 年冷水机厂家最新推荐排行榜:聚焦实力企业,解读技术服务优势与选购指南防爆/低温/水冷/螺杆/超低温冷水机厂家推荐
  • 2025 钢丝绳厂家最新推荐榜:行业标杆与新锐势力深度解析,5 大优质品牌适配场景全指南
  • 2025 地坪研磨机厂家最新推荐榜单:盘点国产优质品牌核心优势及格力 / 宁德时代合作案例 固化剂/水磨石/遥控式/座驾式/小型/大型地坪研磨机厂家推荐
  • windows设置 exe 文件开机启动
  • Linux 与 Windows:哪个操作便捷的系统适合你?
  • 2025 年片材机生产厂家最新推荐排行榜:SMC 片材机组 / 生产线 / 设备 / 辅机优质品牌精选,助力企业精准选购
  • 2025 年宠物托运服务最新推荐榜单:覆盖深港澳 / 高铁托运等场景,爱宠国际领衔优质公司港深宠物托运/珠澳宠物托运公司推荐
  • 50个常见的python毕业设计/课程设计(源码+运行步骤)
  • 2025 年绞车源头厂家最新推荐榜:双速 / 回柱 / 张紧等设备优质直供企业,口碑与实力兼具!张紧/运输/凿井/矿用绞车厂家推荐
  • 2025 年豆腐机厂家最新推荐榜:权威解析企业实力,豆腐豆皮 / 豆干 / 成型设备选购指南厂家推荐
  • set 初始化
  • set查找和统计示例
  • Allegro 输出生产信息详解
  • 2025 年注浆管厂家最新推荐排行榜:聚焦 R780/108 / 隧道 / 预埋 / 桩基专用品类,精选优质企业
  • 编程笔记 - C++ 完美转发
  • MyBatis源码解析:从 Mapper 接口到 SQL 执行的完整链路 - 实践
  • PCIe扫盲——链路初始化与训练基础(一)
  • mysql复杂查询50题mysql面试题
  • 2025 年国内色母粒厂家最新推荐排行榜:聚焦食品级医疗级等多品类,精选综合实力强服务优的企业食品级色母粒/医疗级色母粒 TPU色母粒/透明色母粒/PC色母粒/黑色母粒/白色母粒厂家推荐
  • 2025 波纹管生产厂家最新推荐榜:预应力 / 镀锌金属等品类精选,成都津钢领衔优质品牌清单
  • 2025 年国内废气处理厂商最新推荐排行榜:聚焦综合实力与服务能力,精选优质品牌助企业合规转型
  • 书缘幡云世界(1).众阳之阳.epub
  • Tailwind UnoCSS CSS框架选型
  • 2025 年最新推荐铁附件实力厂家榜单:涵盖电力金具 / 热镀锌 / 线路 / 10 - 35KV 等多类型产品,助力工程方精准筛选优质合作企业
  • 2025 年电力金具厂家最新推荐排行榜:覆盖出口 / 玛钢 / 联板 / 横担 / 抱箍 / 线夹等品类,为采购提供权威参考
  • c++/c语音分号的使用情况
  • PCIe扫盲——物理层逻辑部分基础(三)
  • ArcGIS Pro 3.4 二次开发 - 地图创作 1 - 指南
  • 2025 年镀膜靶材制造厂家最新推荐权威榜单:铬靶 / 镍靶 / 钛靶等优质产品供应商综合实力深度解析