import { ElNotification } from 'element-plus' export const chatMessage = (params, funcs) => { fetch( `${(import.meta as any).env.VITE_WORKFLOW_API_PROXY}/app/chat-messages`, { method: 'POST', body: JSON.stringify(params), headers: { Authorization: localStorage.getItem( (import.meta as any).env.VITE_TOKEN, ), 'Content-Type': 'application/json', } as any, }, ).then((res) => { handleStream({ response: res, ...funcs }) }) } const handleStream = ({ response, onData, onMessageEnd, onStart, onEnd, onError, }) => { if (!response.ok) { onError?.(`${response.status}:${response.statusText}`, response) throw new Error('Network response was not ok') } const reader = response.body?.getReader() const decoder = new TextDecoder('utf-8') let buffer = '' let bufferObj: any = {} const dataFlag = 'data:' const read = () => { let hasError = false reader?.read().then((result: any) => { if (result.done) { onEnd?.() return } buffer += decoder.decode(result.value, { stream: true }) const lines = buffer.split('\n') try { lines.forEach((message) => { if (message.startsWith(dataFlag)) { try { bufferObj = JSON.parse(message.substring(dataFlag.length)) } catch (e) { return } const { event } = bufferObj if (event === 'chat_start') { onStart?.(bufferObj) } else if (event === 'message') { onData(unicodeToChar(bufferObj.answer), bufferObj) } else if (event === 'message_end') { onMessageEnd(bufferObj) } else if (event === 'error') { ElNotification({ title: bufferObj.error_type, message: bufferObj.error_message, type: 'error', duration: 0, }) onError?.(bufferObj.message, bufferObj) } else { console.error(bufferObj) } } }) buffer = lines[lines.length - 1] } catch (e) { hasError = true return } if (!hasError) read() }) } read() } const unicodeToChar = (text: string) => { if (!text) return '' return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => { return String.fromCharCode(parseInt(p1, 16)) }) } // //判断当前浏览器是否支持SSE // let source = '' // if (!!window.EventSource) { // source = new EventSource('http://localhost:8088/sse/') // } else { // thrownewError('当前浏览器不支持SSE') // } // // //对于建立链接的监听 // source.onopen = function (event) { // console.log(source.readyState) // console.log('长连接打开') // } // // //对服务端消息的监听 // source.onmessage = function (event) { // console.log(JSON.parse(event.data)) // console.log('收到长连接信息') // let li = createLi(JSON.parse(event.data)) // document.getElementById('ul').appendChild(li) // } // // //对断开链接的监听 // source.onerror = function (event) { // console.log(source.readyState) // console.log('长连接中断') // }