Browse Source

真流,并显示思考

hongxilin
donghaolin 3 months ago
parent
commit
d795c24332
  1. 133
      src/views/chat.vue

133
src/views/chat.vue

@ -37,7 +37,7 @@ const sessionId = ref(localStorage.getItem('sessionId') || {});
const add = async () => { const add = async () => {
try { try {
const result = await axios.post( const result = await axios.post(
"http://wnxvxx.natappfree.cc/api/v1/chats/8b37cd9cf0c811efa4210242ac120003/completions",
"http://whi3s4.natappfree.cc/api/v1/chats/8b37cd9cf0c811efa4210242ac120003/completions",
{}, {},
{ {
headers: { headers: {
@ -135,78 +135,83 @@ const sendMessage = async () => {
try { try {
// API // API
const response = await fetch("http://wnxvxx.natappfree.cc/api/v1/chats/8b37cd9cf0c811efa4210242ac120003/completions", {
const response = await fetch("http://whi3s4.natappfree.cc/api/v1/chats/8b37cd9cf0c811efa4210242ac120003/completions", {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ragflow-hkNjEwYjcwZjBlMDExZWZiYjYzMDI0Mm' }, headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ragflow-hkNjEwYjcwZjBlMDExZWZiYjYzMDI0Mm' },
body: JSON.stringify({ question: content, stream: false, session_id: sessionId.value })
body: JSON.stringify({ question: content, stream: true, session_id: sessionId.value }) // stream true
}); });
const data = await response.json();
console.log(data, 'data211111');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// //
messages.value = messages.value.filter(msg => !msg.isLoading); messages.value = messages.value.filter(msg => !msg.isLoading);
// data
if (data && data.data && typeof data.data.answer === 'string') {
//
const regex = /<think>(.*?)<\/think>(.*)/s;
const match = data.data.answer.match(regex);
let thinking = '';
let result = data.data.answer;
if (match) {
thinking = match[1].trim();
result = match[2].trim();
}
//
const botMessageIndex = messages.value.length;
messages.value.push({
content: '',
sender: 'bot',
timestamp: new Date()
});
// HTML
let combinedContent = '';
// if (thinking) {
// combinedContent += `<span class="thinking-content">${thinking}</span><br>`;
// }
combinedContent += `<span class="result-content">${result}</span>`;
// 使markedMarkdownHTML
let markdownContent = marked(combinedContent);
// 使 KaTeX
const katexRegex = /\$\$(.*?)\$\$/g;
markdownContent = markdownContent.replace(katexRegex, (match, formula) => {
try {
return katex.renderToString(formula, { throwOnError: false });
} catch (error) {
console.error('KaTeX 渲染错误:', error);
return match;
}
});
//
const botMessageIndex = messages.value.length;
messages.value.push({
content: '',
sender: 'bot',
timestamp: new Date()
});
// 使
let currentIndex = 0;
const intervalId = setInterval(() => {
if (currentIndex < markdownContent.length) {
messages.value[botMessageIndex].content += markdownContent[currentIndex];
scrollToBottom();
currentIndex++;
} else {
clearInterval(intervalId);
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let partialData = '';
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
partialData += decoder.decode(value, { stream: true });
//
const lines = partialData.split('\n');
partialData = lines.pop(); //
for (const line of lines) {
if (line.startsWith('data:')) {
const data = JSON.parse(line.slice(5));
if (data && data.data && typeof data.data.answer === 'string') {
//
const regex = /<think>(.*?)<\/think>(.*)/s;
const match = data.data.answer.match(regex);
let thinking = '';
let result = data.data.answer;
if (match) {
thinking = match[1].trim();
result = match[2].trim();
}
// HTML
let combinedContent = '';
if (thinking) {
combinedContent += `<span class="thinking-content">推理思考:${thinking}</span><br>`;
}
combinedContent += `<span class="result-content">${result}</span>`;
// 使markedMarkdownHTML
let markdownContent = marked(combinedContent);
// 使 KaTeX
const katexRegex = /\$\$(.*?)\$\$/g;
markdownContent = markdownContent.replace(katexRegex, (match, formula) => {
try {
return katex.renderToString(formula, { throwOnError: false });
} catch (error) {
console.error('KaTeX 渲染错误:', error);
return match;
}
});
//
messages.value[botMessageIndex].content = markdownContent;
scrollToBottom();
}
} }
}, 100); // 100
} else {
console.error('API 返回的数据格式不正确:', data);
messages.value.push({
content: '服务返回数据格式错误,请稍后再试',
sender: 'bot',
timestamp: new Date()
});
scrollToBottom();
}
} }
} catch (error) { } catch (error) {
console.error('API请求失败:', error); console.error('API请求失败:', error);

Loading…
Cancel
Save