const getResponse = async (content) => {
try {
const url = '后台地址';
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(content)
});
if (!response.ok) {
throw new Error(`请求失败: ${response.status} ${response.statusText}`);
}
// 创建AI消息(初始为空)
const aiMessageIndex = messages.length;
isLoading.value = false;
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
let lastUpdateTime = 0;
const UPDATE_INTERVAL = 100; // 更新间隔100ms避免频繁渲染
const processChunk = (chunk) => {
buffer += chunk;
// 处理可能的多条数据(以"data: "开头)
while (buffer.includes('data: ')) {
const dataStart = buffer.indexOf('data: ');
const dataEnd = buffer.indexOf('\n', dataStart);
if (dataEnd === -1) break; // 不完整的数据,等待更多
const dataLine = buffer.substring(dataStart + 6, dataEnd).trim();
buffer = buffer.substring(dataEnd + 1);
if (!dataLine) continue;
try {
const parsedData = JSON.parse(dataLine);
if (parsedData.answer) {
// 累积回答内容
messages[aiMessageIndex].content += parsedData.answer;
// 节流更新UI
const now = Date.now();
if (now - lastUpdateTime > UPDATE_INTERVAL) {
scrollToBottom();
lastUpdateTime = now;
}
}
// 检查是否结束
if (parsedData.flag === 'end') {
scrollToBottom(); // 确保最后滚动到底部
return true; // 结束标志
}
} catch (e) {
console.error('解析JSON失败:', e);
}
}
return false;
};
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const shouldBreak = processChunk(chunk);
if (shouldBreak) break;
}
// 处理缓冲区剩余数据
if (buffer.trim()) {
processChunk('');
}
} catch (error) {
console.error('请求异常:', error);
err.value = true;
// 更新最后一条消息显示错误
if (messages.length > 0 && messages[messages.length - 1].sender === 'ai') {
messages[messages.length - 1].content = '服务响应异常,请稍后重试';
} else {
addMessage('ai', '服务响应异常,请稍后重试', '');
}
} finally {
scrollToBottom(); // 最终确保滚动到底部
}
};
07-31
1535
