springboot+langchain4j 实战 Day12 实现流式对话 + 打字机效果的前端聊天页面

Day 12 --- SSE 流式对话

完成内容

目标

实现流式对话 + 打字机效果的前端聊天页面,替代 curl 调试,实现成果可视化。

后端改动

  1. ChatModelConfig.java --- 新增 StreamingChatLanguageModel Bean

    • 使用 OpenAiStreamingChatModel(硅基流动兼容 OpenAI streaming 协议)
    • 超时 120s(流式需要更长等待)
  2. SSEController1.java --- 从 Day1 迁移,适配 Day12 包结构

    • GET /stream/chat?message=xxx
    • 返回 text/event-stream,逐 token 推送
    • SseEmitter 超时 2 分钟
  3. application.yml --- 端口 8088、去 Jasypt、明文 API Key

  4. pom.xml --- 去 Jasypt 依赖、修正包名版本号

前端 (static/index.html)

  • 纯原生 HTML/CSS/JS,零依赖
  • 暗色主题(Tailwind 色板风格)
  • 双模式切换:
    • ⚡ 流式:EventSource → SSE → 逐 token 追加 + 闪烁光标打字机效果
    • 🤖 Agent:fetch /agent/chat → JSON 一次性返回
  • 输入框 + Enter 发送
  • 响应式自适应

验证结果

  • Agent 端点:curl "http://localhost:8088/agent/chat?message=hi"{"code":200,"data":"Hello!..."}
  • SSE 端点:curl "http://localhost:8088/stream/chat?message=你好" → 逐 token 流式输出 ✅
  • 前端页面:http://localhost:8088/index.html 正常加载 ✅

Agent 端点

SSE 端点:居然乱码了

换成postman

前端页面流式输出测试

踩坑:密钥不能加密,不然报错

访问方式

启动项目后浏览器打开 http://localhost:8088/index.html