作者 lixiang

1、智能助手修改回答方式为流式回答

2、修改智能助手页面样式
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { useUserStore } from '/@/store/modules/user'; // 引入用户store获取token
const { createMessage } = useMessage();
... ... @@ -9,43 +10,76 @@ enum Api {
}
/**
* 发送消息
* 发送消息(流式处理)
* @param params
*/
export const sendMessage = async (params: { questionText: string }) => {
try {
const res = await defHttp.get({
url: Api.send,
params,
timeout: 60000
});
console.log("res...",res)
// 确保返回的数据结构正确
if (res ) {
return {
answer: res.answer || '',
similarity: res.similarity || 0,
fileName: res.fileName || '',
fileBase64: res.fileBase64 || null
};
const userStore = useUserStore();
const token = userStore.getToken;
const response = await fetch(
`/jeecgboot/airag/zdyRag/sendStream?questionText=${encodeURIComponent(params.questionText)}`,
{
method: 'GET',
headers: {
'x-access-token': token,
'Accept': 'text/event-stream'
},
credentials: 'include',
}
);
if (!response.ok || !response.body) {
throw new Error(`请求失败: ${response.status} ${response.statusText}`);
}
return null;
// 返回异步生成器函数
return (async function* () {
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data:')) {
try {
const jsonStr = line.substring(5).trim();
if (jsonStr) {
yield JSON.parse(jsonStr); // 直接 yield 解析后的数据
}
} catch (e) {
console.error('JSON解析错误:', e);
}
}
}
}
} finally {
reader.releaseLock();
}
})();
} catch (error) {
console.error("Error sending message:", error);
console.error('Error sending message:', error);
createMessage.error('发送消息失败');
return null;
throw error; // 抛出错误让调用方处理
}
};
export const getButtonList = async () =>{
export const getButtonList = async () => {
const res = await defHttp.get({
url: Api.buttonList,
});
console.log("res",res);
if (res){
if (res) {
return res;
}
return null;
}
... ...
... ... @@ -11,11 +11,17 @@
相似度: {{ (message.similarity * 100).toFixed(2) }}%
<div v-if="message.fileBase64">
相关资料:
<a @click="showPreview(message)">{{message.fileName}}</a>
<a @click="showPreview(message)">{{ message.fileName }}</a>
</div>
</div>
</div>
</div>
<!-- 流式响应时显示的临时消息 -->
<div v-if="streamingMessage" class="message assistant">
<div class="message-content">
<div class="message-text">{{ streamingMessage }}</div>
</div>
</div>
<div v-if="loading" class="message assistant">
<div class="message-content">
<div class="message-text">思考中...</div>
... ... @@ -25,7 +31,6 @@
<!-- 文件预览区域 -->
<div v-if="previewContent" class="file-preview">
<div class="preview-header">
<span class="preview-title">文件预览</span>
<div class="preview-actions">
... ... @@ -58,24 +63,12 @@
</div>
</div>
</div>
<div>
<!-- 快捷按钮区域 -->
<div class="quick-actions">
<a-button
style="margin-left: 1%;
background-color: white;
color: #666;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 16px;
cursor: pointer;
font-size: 14px;
padding: 2px 10px;
width: max-content;
margin-right: 6px;
white-space: nowrap;
transition: all 300ms ease;
"
v-for="(btn, index) in buttonList"
:key="index"
type="primary"
class="action-button"
@click="sendButtonMessage(btn.buttonValues)"
>
... ... @@ -96,6 +89,7 @@
@click="sendMessage"
:loading="loading"
:disabled="!inputMessage.trim()"
class="send-button"
>
发送
</a-button>
... ... @@ -105,7 +99,7 @@
<script lang="ts" name="zdy-rag-chat" setup>
import { ref, reactive, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { sendMessage as apiSendMessage , getButtonList} from './ZdyRag.api';
import { sendMessage as apiSendMessage, getButtonList } from './ZdyRag.api';
import { useMessage } from '/@/hooks/web/useMessage';
import { CloseOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import * as pdfjsLib from 'pdfjs-dist';
... ... @@ -121,12 +115,9 @@ onMounted(async () => {
const res = await getButtonList();
if (res && Array.isArray(res)) {
buttonList.push(...res);
} else {
// createMessage.warning('未获取到按钮列表数据');
}
} catch (error) {
console.error('获取按钮列表失败:', error);
// createMessage.error('获取按钮列表失败');
}
});
... ... @@ -143,6 +134,7 @@ const messages = reactive([
const inputMessage = ref('');
const loading = ref(false);
const streamingMessage = ref(''); // 流式响应消息
const messagesContainer = ref<HTMLElement>();
const previewContent = ref('');
const previewType = ref('');
... ... @@ -167,28 +159,52 @@ const sendMessage = async () => {
inputMessage.value = '';
loading.value = true;
streamingMessage.value = '';
closePreview();
scrollToBottom();
try {
// 调用API发送消息
const res = await apiSendMessage({ questionText: text });
console.log('API响应:', res);
if (res) {
const newMessage = {
type: 'assistant',
text: formatAnswer(res.answer),
similarity: res.similarity || null,
fileBase64: res.fileBase64 || null,
fileName: res.fileName || ''
};
messages.push(newMessage);
} else {
// createMessage.error('获取回答失败: 返回数据为空');
// 创建最终消息对象
const newMessage = {
type: 'assistant',
text: '',
similarity: 0,
fileBase64: null,
fileName: ''
};
// 调用API获取异步生成器
const streamGenerator = await apiSendMessage({ questionText: text });
// 遍历异步生成器
for await (const chunk of streamGenerator) {
if (chunk.token) {
if (!streamingMessage.value){
loading.value = false;
}
streamingMessage.value += chunk.token;
newMessage.text += chunk.token;
scrollToBottom();
} else if (chunk.event === 'END') {
newMessage.similarity = parseFloat(chunk.similarity) || 0;
newMessage.fileName = chunk.fileName || '';
newMessage.fileBase64 = chunk.fileBase64 || null;
}
}
// 将流式消息添加到消息列表
messages.push(newMessage);
streamingMessage.value = '';
} catch (error: any) {
console.error('发送消息失败:', error);
// createMessage.error('发送消息失败: ' + error.message);
messages.push({
type: 'assistant',
text: '请求出错,请稍后重试',
similarity: null,
fileBase64: null,
fileName: null
});
} finally {
loading.value = false;
scrollToBottom();
... ... @@ -208,34 +224,58 @@ const sendButtonMessage = async (buttonValue: string) => {
});
loading.value = true;
streamingMessage.value = '';
closePreview();
scrollToBottom();
try {
// 调用API发送按钮值
const res = await apiSendMessage({ questionText: buttonValue });
if (res) {
const newMessage = {
type: 'assistant',
text: formatAnswer(res.answer),
similarity: res.similarity || null,
fileBase64: res.fileBase64 || null,
fileName: res.fileName || ''
};
messages.push(newMessage);
} else {
console.error('获取回答失败: 返回数据为空');
// 创建最终消息对象
const newMessage = {
type: 'assistant',
text: '',
similarity: 0,
fileBase64: null,
fileName: ''
};
// 调用API获取异步生成器
const streamGenerator = await apiSendMessage({ questionText: buttonValue });
// 遍历异步生成器
for await (const chunk of streamGenerator) {
if (chunk.token) {
if (!streamingMessage.value){
loading.value = false;
}
streamingMessage.value += chunk.token;
newMessage.text += chunk.token;
scrollToBottom();
} else if (chunk.event === 'END') {
newMessage.similarity = parseFloat(chunk.similarity) || 0;
newMessage.fileName = chunk.fileName || '';
newMessage.fileBase64 = chunk.fileBase64 || null;
}
}
// 将流式消息添加到消息列表
messages.push(newMessage);
streamingMessage.value = '';
} catch (error: any) {
console.error('发送按钮消息失败:', error);
// createMessage.error('发送按钮消息失败: ' + error.message);
messages.push({
type: 'assistant',
text: '请求出错,请稍后重试',
similarity: null,
fileBase64: null,
fileName: null
});
} finally {
loading.value = false;
scrollToBottom();
}
};
// 增强版showPreview函数
// 显示文件预览
const showPreview = async (message: any) => {
try {
// 验证基本数据
... ... @@ -275,7 +315,6 @@ const showPreview = async (message: any) => {
} catch (error) {
console.error('预览失败:', error);
previewContent.value = 'error';
// createMessage.error(`预览失败: ${error.message}`);
}
};
... ... @@ -365,7 +404,6 @@ const decodeBase64Content = (base64: string): string => {
// 下载文件
const downloadFile = () => {
if (!currentFile.value || !currentFile.value.fileBase64 || !currentFile.value.fileName) {
// createMessage.warning('无法下载文件');
return;
}
... ... @@ -384,11 +422,8 @@ const downloadFile = () => {
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// createMessage.success('文件下载开始');
} catch (error: any) {
console.error('文件下载失败:', error);
// createMessage.error('文件下载失败: ' + error.message);
}
};
... ... @@ -407,12 +442,6 @@ const closePreview = () => {
if (docxPreview.value) docxPreview.value.innerHTML = '';
};
// 格式化回答内容
const formatAnswer = (answer: string) => {
// 替换[n]为换行符,然后将换行符转换为<br>标签
return answer.replace(/\[n\]/g, '\n').replace(/\n/g, '<br>');
};
// 滚动到底部
const scrollToBottom = () => {
nextTick(() => {
... ... @@ -429,16 +458,17 @@ onBeforeUnmount(() => {
</script>
<style lang="less" scoped>
/* 样式保持不变 */
.chat-container {
display: flex;
flex-direction: column;
height: calc(100vh - 120px);
max-width: 1200px;
height: calc(100vh - 60px);
max-width: 100%;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
border-radius: 8px;
background-color: #f9fafb;
border-radius: 16px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.main-content {
... ... @@ -447,151 +477,83 @@ onBeforeUnmount(() => {
gap: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #fff;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 15px;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
background-color: #fff;
border-radius: 12px;
min-height: 300px;
display: flex;
flex-direction: column;
}
//.file-preview {
// width: 55%;
// min-width: 300px;
// display: flex;
// flex-direction: column;
// background-color: white;
// border-radius: 8px;
// box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
// overflow: hidden;
//
// .preview-header {
// display: flex;
// justify-content: space-between;
// align-items: center;
// padding: 10px 15px;
// background-color: #f0f0f0;
// border-bottom: 1px solid #e8e8e8;
//
// .preview-actions {
// display: flex;
// align-items: center;
// gap: 8px;
// }
// }
//
// .preview-content {
// flex: 1;
// overflow: auto;
// padding: 10px;
//
// .text-preview {
// padding: 15px;
// white-space: pre-wrap;
// font-family: monospace;
// line-height: 1.6;
// }
//
// .pdf-preview {
// height: 100%;
// overflow-y: auto;
//
// .pdf-pages {
// display: flex;
// flex-direction: column;
// gap: 20px;
// padding: 10px;
//
// .pdf-page {
// border: 1px solid #e8e8e8;
// box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
// }
// }
// }
//
// .docx-preview {
// height: 100%;
// overflow-y: auto;
// padding: 20px;
// background-color: #fff;
// }
//
// .unsupported-preview {
// height: 100%;
// padding: 20px;
// display: flex;
// align-items: center;
// justify-content: center;
// color: #ff4d4f;
// font-weight: 500;
// }
// }
//}
.file-preview {
width: 55%;
width: 50%;
min-width: 300px;
display: flex;
flex-direction: column;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
overflow: hidden;
border-left: 1px solid #eaeaea;
.preview-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background-color: #f0f0f0;
padding: 12px 16px;
background-color: #f5f7fa;
border-bottom: 1px solid #e8e8e8;
font-weight: 500;
font-size: 14px;
font-weight: 600;
font-size: 16px;
color: #2d3748;
.preview-actions {
display: flex;
align-items: center;
gap: 10px;
gap: 8px;
.ant-btn {
padding: 0;
height: auto;
color: #666;
color: #4a5568;
display: flex;
align-items: center;
transition: color 0.3s;
&:hover {
color: #1890ff;
background: transparent;
color: #3182ce;
}
.anticon {
font-size: 16px;
margin-right: 4px;
}
}
.ant-btn-link {
padding: 0 8px;
}
}
}
.preview-content {
flex: 1;
overflow: auto;
padding: 10px;
padding: 16px;
.text-preview {
padding: 15px;
padding: 16px;
white-space: pre-wrap;
font-family: monospace;
font-family: 'Consolas', monospace;
line-height: 1.6;
background-color: #fafafa;
border-radius: 4px;
background-color: #f8fafc;
border-radius: 8px;
font-size: 14px;
color: #2d3748;
}
.pdf-preview {
... ... @@ -606,7 +568,7 @@ onBeforeUnmount(() => {
.pdf-page {
border: 1px solid #e8e8e8;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
background-color: white;
}
}
... ... @@ -627,86 +589,101 @@ onBeforeUnmount(() => {
display: flex;
align-items: center;
justify-content: center;
color: #ff4d4f;
color: #e53e3e;
font-weight: 500;
background-color: #fff2f0;
background-color: #fff5f5;
border-radius: 4px;
text-align: center;
}
}
}
/* 响应式设计 */
@media (max-width: 768px) {
.file-preview {
width: 100%;
min-width: auto;
max-height: 300px;
.preview-header {
padding: 8px 12px;
.quick-actions {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 20px;
padding: 0 10px;
.preview-actions {
gap: 6px;
.action-button {
background-color: white;
color: #4a5568;
border: 1px solid #e2e8f0;
border-radius: 16px;
cursor: pointer;
font-size: 14px;
padding: 6px 16px;
transition: all 0.3s ease;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
.ant-btn-link {
padding: 0 4px;
}
}
&:hover {
background-color: #edf2f7;
transform: translateY(-2px);
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}
.preview-content {
padding: 8px;
.text-preview,
.docx-preview {
padding: 10px;
}
&:active {
transform: translateY(0);
}
}
}
.message {
margin-bottom: 15px;
margin-bottom: 20px;
display: flex;
max-width: 85%;
animation: fadeIn 0.3s ease;
&.user {
align-self: flex-end;
justify-content: flex-end;
.message-content {
background-color: #1890ff;
background-color: #3182ce;
color: white;
border-radius: 18px 18px 0 18px;
}
}
&.assistant {
align-self: flex-start;
justify-content: flex-start;
.message-content {
background-color: #f0f0f0;
color: #333;
background-color: #edf2f7;
color: #2d3748;
border-radius: 18px 18px 18px 0;
}
}
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.message-content {
max-width: 80%;
padding: 12px 16px;
padding: 14px 18px;
word-wrap: break-word;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
line-height: 1.5;
}
.message-text {
font-size: 15px;
}
.message-meta {
font-size: 12px;
color: #666;
color: #718096;
margin-top: 8px;
text-align: right;
a {
margin-left: 10px;
color: #1890ff;
color: #3182ce;
cursor: pointer;
font-weight: 500;
&:hover {
text-decoration: underline;
... ... @@ -718,45 +695,88 @@ onBeforeUnmount(() => {
display: flex;
gap: 12px;
padding: 10px 0;
background: white;
border-radius: 12px;
padding: 15px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
:deep(.ant-input) {
flex: 1;
border-radius: 20px;
padding: 12px 18px;
border: 1px solid #d9d9d9;
border-radius: 24px;
padding: 14px 20px;
border: 1px solid #e2e8f0;
transition: all 0.3s;
font-size: 15px;
height: auto;
&:hover {
border-color: #40a9ff;
border-color: #a0aec0;
}
&:focus {
box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
border-color: #3182ce;
box-shadow: 0 0 0 2px rgba(49, 130, 206, 0.2);
}
}
.ant-btn {
border-radius: 20px;
padding: 0 24px;
height: 40px;
font-weight: 500;
.send-button {
border-radius: 24px;
padding: 0 28px;
height: 48px;
font-weight: 600;
background-color: #3182ce;
border: none;
transition: all 0.3s;
&:hover {
background-color: #2b6cb0 !important;
transform: translateY(-2px);
}
&:active {
transform: translateY(0);
}
}
}
/* 响应式设计 */
@media (max-width: 768px) {
.chat-container {
height: calc(100vh - 20px);
padding: 10px;
}
.main-content {
flex-direction: column;
height: auto;
}
.file-preview {
width: 100%;
min-width: auto;
max-height: 300px;
border-left: none;
border-top: 1px solid #eaeaea;
.preview-header {
padding: 10px 12px;
}
}
.message-content {
.message {
max-width: 90%;
}
.chat-input {
flex-direction: column;
.send-button {
width: 100%;
}
}
.quick-actions {
justify-content: center;
}
}
</style>
... ...