stock-ai-agent/frontend/test-stream.html
2026-02-03 22:48:45 +08:00

117 lines
4.0 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>流式输出测试</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
background: #1a1a1a;
color: #fff;
}
#output {
border: 1px solid #333;
padding: 20px;
min-height: 200px;
background: #000;
white-space: pre-wrap;
margin: 20px 0;
}
button {
padding: 10px 20px;
background: #00ff41;
color: #000;
border: none;
cursor: pointer;
font-size: 16px;
}
button:hover {
background: #00cc33;
}
.status {
color: #00ff41;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>流式输出测试</h1>
<button onclick="testStream()">测试流式输出</button>
<div class="status" id="status"></div>
<div id="output"></div>
<script>
async function testStream() {
const output = document.getElementById('output');
const status = document.getElementById('status');
output.textContent = '';
status.textContent = '正在连接...';
try {
const response = await fetch('/api/chat/message/stream', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'text/event-stream',
'Cache-Control': 'no-cache'
},
body: JSON.stringify({
message: '你好',
session_id: 'test_' + Date.now()
})
});
status.textContent = '已连接,正在接收数据...';
console.log('Response status:', response.status);
console.log('Response headers:', [...response.headers.entries()]);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let chunkCount = 0;
while (true) {
const { done, value } = await reader.read();
chunkCount++;
console.log(`Chunk ${chunkCount}: ${value ? value.length : 0} bytes, done=${done}`);
if (done) {
status.textContent = '完成!共接收 ' + chunkCount + ' 个数据块';
break;
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
console.log('Data:', data);
if (data.type === 'content') {
output.textContent += data.content;
} else if (data.type === 'done') {
status.textContent = '流式输出完成!共接收 ' + chunkCount + ' 个数据块';
} else if (data.type === 'error') {
status.textContent = '错误: ' + data.error;
output.textContent += '\n\n错误: ' + data.error;
}
} catch (e) {
console.error('Parse error:', e, line);
}
}
}
}
} catch (error) {
status.textContent = '错误: ' + error.message;
console.error('Error:', error);
}
}
</script>
</body>
</html>