本文介绍如何使用spring ai和简单html,与llm大预言模型进行简单的对话。下文的代码基于
《# 使用Spring AI和大预言模型交互Helloworld篇》实现。
SSE技术介绍
SSE(Server-Sent Events)技术是一种用于在Web应用程序中实现服务器到客户端的单向实时消息推送的技术。通过SSE,服务器可以主动向客户端发送更新,而不需要客户端不断地请求数据。其工作原理如下:
1. 连接建立:客户端通过HTTP请求与服务器建立连接,通常是通过 `EventSource` 对象。
2. 数据推送:服务器持续发送文本数据,数据格式通常是以特定格式(如文本/event-stream)发送。
3. 自动重连:如果连接意外中断,客户端会自动尝试重新连接。
SSE适用于需要实时更新的场景,如聊天应用、通知系统和股票价格更新等。相比于WebSocket,SSE实现更简单,但仅支持单向通信。
开发SSE接口
@GetMapping(value = "/ai/generate4", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> generate4(@RequestParam(value = "message", defaultValue = "告诉我5部关于周星驰的电影") String message) {
return this.chatClient.prompt()
.user(message)
.stream()
.content();
}
注意在@GetMapping注解里,要加入produces = MediaType.TEXT_EVENT_STREAM_VALUE属性。
通过 MediaType.TEXT_EVENT_STREAM_VALU告诉浏览器,这个是sse接口。

开发一张简单的html网页
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>大语言模型问答页面</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/2.1.3/marked.min.js"></script>
<style> body {
font-family: Arial, sans-serif;
margin: 20px;
}
#response {
border: 1px solid #ccc;
padding: 10px;
margin-top: 10px;
min-height: 100px;
white-space: pre-wrap; /* 保持空格和换行 */ }
/* 添加样式以格式化 Markdown 内容 */ .markdown-body {
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f9f9f9;
}
</style>
</head>
<body>
<h1>大语言模型问答页面</h1>
<textarea id="input" rows="4" cols="50" placeholder="请输入您的问题..."></textarea><br>
<button id="submit">提交问题</button>
<h2>回答:</h2>
<div id="response" class="markdown-body"></div>
<script>
$(document).ready(function() {
$('#submit').click(function() {
const message = $('#input').val();
if (!message) {
alert("请输入问题!");
return;
}
// 清空之前的响应
$('#response').text('');
// 使用 EventSource 连接到服务器
const eventSource = new EventSource(`/ai/generate4?message=${encodeURIComponent(message)}`);
// 监听消息事件
eventSource.onmessage = function(event) {
console.log(event);
$('#response').append(event.data);
};
// 监听错误事件
eventSource.onerror = function(event) {
console.error("EventSource failed:", event);
eventSource.close(); // 关闭连接
};
// 监听连接关闭事件
eventSource.onclose = function() {
console.log("EventSource connection closed.");
$('#response').text(marked($('#response').val()));
};
});
});
</script>
</body>
</html>
js代码里使用了EventSource对象,用于sse的通讯。
运行效果
