feat: 实现伪流式接口,实时展示 LLM 执行步骤

- 新增 StreamingStepAdvisor 捕获每个执行步骤(工具调用、响应等)
- 在 ChatService 中实现 chatStreamWithTools 方法
- 使用 SSE 实时推送执行步骤到前端
- 新增 /api/chat/stream-with-tools 接口
- 创建测试页面 stream-test.html 展示实时步骤

功能特性:
- 实时显示用户消息
- 实时显示工具调用(工具名称、参数)
- 实时显示工具响应
- 实时显示 AI 文本响应
- 支持错误处理和显示

访问地址:http://localhost:8080/stream-test.html

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-30 16:15:37 +08:00
1 parent 85b3130514
commit 0c5655af5b
4 files changed
+635

No files matched your search

+420
View File
@@ -0,0 +1,420 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>伪流式聊天测试 - Spring AI Skills Demo</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
width: 100%;
max-width: 900px;
height: 80vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
text-align: center;
}
.header h1 {
font-size: 24px;
margin-bottom: 5px;
}
.header p {
font-size: 14px;
opacity: 0.9;
}
.chat-area {
flex: 1;
overflow-y: auto;
padding: 20px;
background: #f5f5f5;
}
.message {
margin-bottom: 15px;
animation: fadeIn 0.3s ease-in;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.message.user {
text-align: right;
}
.message-content {
display: inline-block;
max-width: 70%;
padding: 12px 16px;
border-radius: 18px;
word-wrap: break-word;
}
.message.user .message-content {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.message.assistant .message-content {
background: white;
color: #333;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.step {
margin: 10px 0;
padding: 10px;
background: #e3f2fd;
border-left: 4px solid #2196F3;
border-radius: 4px;
font-size: 14px;
}
.step.tool-call {
background: #fff3e0;
border-left-color: #ff9800;
}
.step.tool-response {
background: #e8f5e9;
border-left-color: #4caf50;
}
.step.error {
background: #ffebee;
border-left-color: #f44336;
}
.step-type {
font-weight: bold;
margin-bottom: 5px;
display: flex;
align-items: center;
}
.step-type::before {
content: '●';
margin-right: 8px;
font-size: 12px;
}
.step.tool-call .step-type::before {
color: #ff9800;
}
.step.tool-response .step-type::before {
color: #4caf50;
}
.step-content {
font-family: 'Courier New', monospace;
font-size: 13px;
color: #555;
white-space: pre-wrap;
}
.input-area {
padding: 20px;
background: white;
border-top: 1px solid #e0e0e0;
}
.input-container {
display: flex;
gap: 10px;
}
#messageInput {
flex: 1;
padding: 12px 16px;
border: 2px solid #e0e0e0;
border-radius: 25px;
font-size: 14px;
outline: none;
transition: border-color 0.3s;
}
#messageInput:focus {
border-color: #667eea;
}
#sendButton {
padding: 12px 30px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 25px;
font-size: 14px;
font-weight: bold;
cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s;
}
#sendButton:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
#sendButton:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: white;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #555;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🤖 伪流式聊天测试</h1>
<p>实时展示 LLM 的每个执行步骤(工具调用、响应等)</p>
</div>
<div class="chat-area" id="chatArea">
<div class="message assistant">
<div class="message-content">
你好!我是 AI 助手。我可以使用多种工具来帮助你,包括:<br>
• 定价 Skills(客户评级、定价计算等)<br>
• MCP 工具(获取风险成本)<br>
• TodoWrite(任务管理)<br>
• 文件操作和 Shell 命令<br><br>
试试问我:"请帮我为某某公司进行定价"
</div>
</div>
</div>
<div class="input-area">
<div class="input-container">
<input type="text" id="messageInput" placeholder="输入消息..." />
<button id="sendButton" onclick="sendMessage()">发送</button>
</div>
</div>
</div>
<script>
const chatArea = document.getElementById('chatArea');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
let conversationId = generateUUID();
let currentStepsContainer = null;
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function addMessage(content, isUser = false) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${isUser ? 'user' : 'assistant'}`;
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
contentDiv.textContent = content;
messageDiv.appendChild(contentDiv);
chatArea.appendChild(messageDiv);
chatArea.scrollTop = chatArea.scrollHeight;
// 如果是助手消息,创建步骤容器
if (!isUser) {
currentStepsContainer = document.createElement('div');
currentStepsContainer.style.marginLeft = '20px';
chatArea.appendChild(currentStepsContainer);
}
}
function addStep(type, data) {
if (!currentStepsContainer) return;
const stepDiv = document.createElement('div');
stepDiv.className = `step ${type}`;
const typeDiv = document.createElement('div');
typeDiv.className = 'step-type';
let typeText = '';
let contentText = '';
switch(type) {
case 'tool-call':
typeText = `🔧 调用工具: ${data.tool_name}`;
contentText = `参数: ${data.arguments}`;
break;
case 'tool-response':
typeText = `✅ 工具响应: ${data.tool_name}`;
contentText = data.response;
break;
case 'assistant-message':
typeText = '💬 AI 响应';
contentText = data.content;
break;
case 'error':
typeText = '❌ 错误';
contentText = data.message;
break;
}
typeDiv.textContent = typeText;
stepDiv.appendChild(typeDiv);
if (contentText) {
const contentDiv = document.createElement('div');
contentDiv.className = 'step-content';
contentDiv.textContent = contentText;
stepDiv.appendChild(contentDiv);
}
currentStepsContainer.appendChild(stepDiv);
chatArea.scrollTop = chatArea.scrollHeight;
}
async function sendMessage() {
const message = messageInput.value.trim();
if (!message) return;
// 禁用输入
messageInput.disabled = true;
sendButton.disabled = true;
sendButton.innerHTML = '<span class="loading"></span>';
// 显示用户消息
addMessage(message, true);
messageInput.value = '';
try {
const response = await fetch(`/api/chat/stream-with-tools?conversationId=${conversationId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: message })
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n\n');
buffer = lines.pop(); // 保留不完整的行
for (const line of lines) {
if (line.startsWith('event:')) {
const eventMatch = line.match(/event: (\w+)/);
const dataMatch = line.match(/data: (.+)/);
if (eventMatch && dataMatch) {
const eventType = eventMatch[1];
const data = JSON.parse(dataMatch[1]);
if (eventType === 'user_message') {
// 用户消息已经显示,跳过
} else if (eventType === 'tool_call') {
addStep('tool-call', data);
} else if (eventType === 'tool_response') {
addStep('tool-response', data);
} else if (eventType === 'assistant_message') {
addStep('assistant-message', data);
} else if (eventType === 'final_response') {
// 最终响应已经通过步骤显示,这里可以添加总结
} else if (eventType === 'error') {
addStep('error', data);
}
}
}
}
}
} catch (error) {
console.error('Error:', error);
addMessage('发送失败: ' + error.message, false);
} finally {
// 恢复输入
messageInput.disabled = false;
sendButton.disabled = false;
sendButton.textContent = '发送';
messageInput.focus();
currentStepsContainer = null;
}
}
// 回车发送
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
// 页面加载完成后聚焦输入框
window.addEventListener('load', () => {
messageInput.focus();
});
</script>
</body>
</html>