123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- 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('长连接中断')
- // }
|