-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsse.js
69 lines (67 loc) · 2.29 KB
/
sse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { fetchEventSource } from '@microsoft/fetch-event-source';
export function sendMsg() {
let response = ''
let signal = new AbortController()
const userMsg = document.getElementById('input').value
const body = {
messages: [{role:'user',content:userMsg}],
}
const apiKey = ''
fetchEventSource('https://playground.judini.ai/api/v1/agent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer '+ apiKey
},
body: JSON.stringify(body),
bodyTimeout: 0,
headersTimeout: 0,
signal: signal.signal,
async onopen (response) {
if (response.status === 200) {
console.log('Connected to chat')
return
}
let error
try {
const body = await response.text()
error = new Error(`Failed to send message. HTTP ${response.status} - ${body}`)
error.status = response.status
error.json = JSON.parse(body)
} catch {
error = error || new Error(`Failed to send message. HTTP ${response.status}`)
}
throw error
},
onclose () {
console.log('Connection closed')
},
onerror (err) {
console.error('Connection error', err)
throw err
},
openWhenHidden: true, // open the connection even if the tab is hidden
onmessage (msg) {
if (msg.data.includes('data: [DONE]')) {
signal.abort()
return
}// msg.data
try {
const data = msg.data.split('\n\n')
for (let i = 0; i < data.length; i++) {
const element = JSON.parse(data[i].replace('data: ', ''))
if (element.data !== undefined) {
response += element.data
updateTextArea(response) // update the text area with the response gradually
}
}
} catch (e) {
console.error(e)
}
}
})
}
function updateTextArea(text) {
const textArea = document.getElementById('textArea')
textArea.value = text
}