uni-app 在 UniApp 中实现stream流式输出 AI 聊天功能,AI输出内容用Markdown格式展示 - )) {
在 UniApp 中实现流式 AI 聊天功能
介绍
在现代 Web 开发中,流式 API 响应能够显著提升用户体验,尤其是在与 AI 聊天接口进行交互时。本文将介绍如何在 UniApp 中使用 Fetch API 实现一个流式响应的 AI 聊天功能,包括实时更新聊天内容和滚动到底部的功能。
实现
用 Markdown 格式展示 AI 输出的内容
class="message-avatar"
src="/static/images/icon_robot.png" 拼多多帮助力入口
/>
v-if="
isSendLoading &&
index == chatMessages.length - 1 &&
!getText(message.content)
"
>
// 用Markdown格式展示
class="message-text"
:content="message.content"
/>
// 使用showdown插件
我们需要使用 Fetch API 向 AI 聊天服务发送请求,并读取其流式响应。以下是实现的关键代码段。
async getAIChat(params, aiMessage) {
// 使用 Fetch API 进行流式请求
const response = await fetch(`${config.aiBaseUrl}/api/v1/chat/completions`, {
method: 'POST',
headers: {
Authorization: `Bearer ${config.apikey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(params),
});
// 检测响应状态
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || '请求失败');
}
this.isSendLoading = false; // 更新加载状态
// 使用 response.body.getReader() 开始逐块读取流式响应,使用 UTF-8 编码解码数据。
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let done = false;
// 用于流式读取数据
while (!done) {
const { done: readerDone, value } = await reader.read();
done = readerDone;
if (value) {
// 逐块解码并拼接
const chunkText = decoder.decode(value, { stream: !done });
// 解析接收到的 JSON 数据
const lines = chunkText.split('\n'); // 按行分割
lines.forEach((line) => {
if (line.startsWith('data:')) {
const jsonString = line.substring(5).trim();
try {
const jsonData = JSON.parse(jsonString);
// 提取内容部分
const content = jsonData.choices?.[0]?.delta?.content || '';
if (content) {
aiMessage.content += content; // 更新聊天内容
// 清除开头的换行符
if (aiMessage.content.startsWith('\n')) {
aiMessage.content = aiMessage.content.slice(1);
}
// 刷新页面渲染
this.$forceUpdate(); // 确保视图更新
// 滚动到底部
this.$nextTick(() => {
this.scrollToBottom(); // 调用滚动到底部的方法
});
}
} catch (error) {
console.error('Error parsing JSON:', error);
}
}
});
}
}
}
uni-app 在 UniApp 中实现stream流式输出 AI 聊天功能,AI输出内容用Markdown格式展示
相关链接