-
Notifications
You must be signed in to change notification settings - Fork 0
/
cheshire-cat-chat-widget.js
91 lines (69 loc) · 2.16 KB
/
cheshire-cat-chat-widget.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import CatClient from 'https://cdn.jsdelivr.net/npm/ccat-api@0.10.6/+esm'
let ccat
const thinkingMessage = "Thinking..."
const firstMessage = "How can I help you? \n\nPlease remember I'm an AI, so I may be wrong. Be sure to verify my responses."
document.addEventListener('alpine:init', function () {
initCat()
initAlpineStore()
})
const initAlpineStore = () => {
Alpine.store("store", {
waitingFirstToken: false,
waitingLastToken: false,
query: "",
messages: [firstMessage],//"stocazzoooooooooooooooooooooooooo".split(""),
send: function () {
ccat.send(this.query, {
"custom": "more data"
})
this.messages.push(this.query)
this.messages.push(thinkingMessage)
this.waitingFirstToken = true
this.waitingLastToken = true
this.query = ""
let historyEl = this.$refs.history
setTimeout(function(){
scrollDown(historyEl)
})
}
})
}
function initCat() {
ccat = new CatClient({
baseUrl: 'localhost',
userId: 'peepino'
})
ccat.onMessage((msg) => {
console.log(msg)
let store = Alpine.store("store")
let nMessages = store.messages.length
if(msg.type == "chat_token") {
if(store.waitingFirstToken){
store.messages[nMessages - 1] = msg.content
store.waitingFirstToken = false
} else {
store.messages[nMessages - 1] += msg.content
}
}
if(msg.type == "chat") {
store.messages[nMessages - 1] = msg.content
store.waitingLastToken = false
}
if(msg.type == "notification") {
console.warn("Notification")
console.warn(msg.content)
}
// scroll down chat history
scrollDown(store.$refs.history)
})
ccat.onError = function (msg) {
console.error(msg)
}
console.log(ccat)
}
function scrollDown(el){
el.scrollTo({
top: el.scrollHeight,
behavior: "instant"
})
}