概述
不论是GPT还是文心一言,在回答的时候类似于打字机式的将答案呈现给我们,这样的交互一方面比较友好,另一方面,当答案比较多、生成比较慢的时候也能争取一些答案的生成时间。本文后端使用express
和stream
,使用SSE将结果逐渐输出,前端使用v-md-editor
对返回的结果进行呈现。
实现效果
实现
1. 后端
const stream = require("stream");
const R = require('../utils/result')let sse = null,contentId = 0,flag = 0;function toDataString(data) {if (typeof data === "object") return toDataString(JSON.stringify(data));return data.split(/\r\n|\r|\n/).map((line) => `data: ${line}\n`).join("");
}const messageStr = `JavaScript中常用的排序算法有以下几种:1. 冒泡排序冒泡排序是一种简单的排序算法,它重复地遍历要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。遍历数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。\`\`\`javascript
function bubbleSort(arr) {var len = arr.length;for (var i = 0; i < len - 1; i++) {for (var j = 0; j < len - 1 - i; j++) {if (arr[j] > arr[j + 1]) {[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];}}}return arr;
}
\`\`\`2. 选择排序选择排序是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。\`\`\`javascript
function selectionSort(arr) {var len = arr.length;for (var i = 0; i < len - 1; i++) {var minIndex = i;for (var j = i + 1; j < len; j++) {if (arr[j] < arr[minIndex]) {minIndex = j;}}[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];}return arr;
}
\`\`\`3. 插入排序插入排序的工作原理是通过构造一个有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。\`\`\`javascript
function insertionSort(arr) {var len = arr.length;for (var i = 1; i < len; i++) {var key = arr[i];var j = i - 1;while (j >= 0 && arr[j] > key) {arr[j + 1] = arr[j];j--;}arr[j + 1] = key;}return arr;
}
\`\`\`4. 快速排序快速排序是一种高效的排序算法,它的基本思想是使用分治法。\`\`\`javascript
function quickSort(arr, left = 0, right = arr.length - 1) {if (left < right) {let pivotIndex = partition(arr, left, right);quickSort(arr, left, pivotIndex - 1);quickSort(arr, pivotIndex + 1, right);}return arr;
}function partition(arr, left, right) {let pivotValue = arr[right];let pivotIndex = left;for (let i = left; i < right; i++) {if (arr[i] <= pivotValue) {[arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]];pivotIndex++;}}[arr[pivotIndex], arr[right]] = [arr[right], arr[pivotIndex]];return pivotIndex;
}
\`\`\`5. 归并排序归并排序是建立在归并操作上的一种有效的排序算法,效率为O(nlogn)。\`\`\`javascript
function mergeSort(arr) {if (arr.length < 2) {return arr;}var mid = Math.floor(arr.length / 2);var left = arr.slice(0, mid);var right = arr.slice(mid);return merge(mergeSort(left), mergeSort(right));
}function merge(left, right) {var result = [];while (left.length && right.length) {if (left[0] <= right[0]) {result.push(left.shift());} else {result.push(right.shift());}}while (left.length) {result.push(left.shift());}while (right.length) {result.push(right.shift());}return result;
}
\`\`\`以上就是JavaScript中常见的几种排序算法,每种算法都有其适用的场景和优缺点,根据实际需求选择合适的排序算法可以提高程序的运行效率。`const gptController = {getAnswer: async function (req, res, next) {// 触动定时触发let index = 0clearInterval(flag)flag = setInterval(() => {const r = new R();if(index < messageStr.length) {const message = {data: r.ok({msg: messageStr.slice(0, index + 1)}),event: "dynamicUpdate", // 事件类型,需要客户端添加对应的事件监听id: ++contentId,retry: 2000,};sse?.write(message);index += 1} else {const message = {data: r.ok({msg: 'end'}),event: "dynamicUpdate", // 事件类型,需要客户端添加对应的事件监听id: ++contentId,retry: 2000,};sse?.write(message);clearInterval(flag)}}, 60);res.writeHead(200, {"Content-Type": "text/event-stream; charset=utf-8",});sse = new stream.Transform({ objectMode: true });sse._transform = (message, encoding, callback) => {if (message.comment) sse.push(`: ${message.comment}\n`);if (message.event) sse.push(`event: ${message.event}\n`);if (message.id) sse.push(`id: ${message.id}\n`);if (message.retry) sse.push(`retry: ${message.retry}\n`);if (message.data) sse.push(toDataString(message.data));sse.push("\n");callback();};sse.write(":ok\n\n");sse.pipe(res);},
};module.exports = gptController;
2. 前端实现
在主入口引入v-md-editor
。
// main.js
import VMdPreview from '@kangc/v-md-editor/lib/preview';
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js';
import createCopyCodePlugin from '@kangc/v-md-editor/lib/plugins/copy-code/index';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import '@kangc/v-md-editor/lib/style/preview.css';
import '@kangc/v-md-editor/lib/plugins/copy-code/copy-code.css';
import '@kangc/v-md-editor/lib/theme/style/vuepress.css';
import '@kangc/v-md-editor/lib/style/codemirror-editor.css';
import '@kangc/v-md-editor/lib/theme/style/github.css';
import createLineNumbertPlugin from '@kangc/v-md-editor/lib/plugins/line-number/index';
import '@kangc/v-md-editor/lib/plugins/tip/tip.css';
import Prism from 'prismjs';VMdPreview.use(vuepressTheme, { Prism });
VMdPreview.use(createCopyCodePlugin());
VMdPreview.use(createLineNumbertPlugin());const app = createApp(App)
app.use(VMdPreview).mount('#app')
页面引用v-md-preview
。
<template><div class="app"><v-md-preview :text="mdText"></v-md-preview></div>
</template><script>
export default {data() {return {mdText: "",};},mounted() {const that = thisconst es = new EventSource("http://localhost:8080/gpt/sse");es.addEventListener("dynamicUpdate", (e) => {const data = JSON.parse(e.data);const msg = data.data.msg;if (msg === "end") {es.close();} else {that.mdText = msg}});es.onopen = () => {console.log("已开启。。。");};es.onmessage = (e, me) => {console.log("默认推送:" + e.data);};es.onerror = (err) => {console.log(err);};},
};
</script><style scoped>
.app {width: 100%;height: 100%;
}
</style>