-
Notifications
You must be signed in to change notification settings - Fork 16
/
StreamingChatView.tsx
48 lines (41 loc) · 1.45 KB
/
StreamingChatView.tsx
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
import {useState} from "react";
import {MessageList, MessageListItem} from "@hilla/react-components/MessageList";
import {ChatService} from "Frontend/generated/endpoints";
import {MessageInput} from "@hilla/react-components/MessageInput";
export default function StreamingChatView() {
const [messages, setMessages] = useState<MessageListItem[]>([]);
function addMessage(message: MessageListItem) {
setMessages(messages => [...messages, message]);
}
function appendToLastMessage(chunk: string) {
setMessages(messages => {
const lastMessage = messages[messages.length - 1];
lastMessage.text += chunk;
return [...messages.slice(0, -1), lastMessage];
});
}
async function sendMessage(message: string) {
addMessage({
text: message,
userName: 'You'
});
let first = true;
ChatService.chatStream(message).onNext(chunk => {
if (first && chunk) {
addMessage({
text: chunk,
userName: 'Assistant'
});
first = false;
} else {
appendToLastMessage(chunk);
}
});
}
return (
<div className="p-m flex flex-col h-full box-border">
<MessageList items={messages} className="flex-grow"/>
<MessageInput onSubmit={e => sendMessage(e.detail.value)}/>
</div>
);
}