RWKV-Runner/frontend/src/pages/Chat.tsx

324 lines
12 KiB
TypeScript
Raw Normal View History

2023-06-14 12:26:04 +00:00
import React, { FC, useEffect, useRef } from 'react';
2023-05-21 05:48:11 +00:00
import { useTranslation } from 'react-i18next';
2023-05-24 13:27:23 +00:00
import { Avatar, PresenceBadge, Textarea } from '@fluentui/react-components';
2023-05-21 05:48:11 +00:00
import commonStore, { ModelStatus } from '../stores/commonStore';
import { observer } from 'mobx-react-lite';
import { v4 as uuid } from 'uuid';
2023-05-19 06:22:37 +00:00
import classnames from 'classnames';
2023-05-21 05:48:11 +00:00
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { ConversationPair, getConversationPairs, Record } from '../utils/get-conversation-pairs';
2023-06-03 12:18:57 +00:00
import logo from '../assets/images/logo.jpg';
2023-05-19 07:40:17 +00:00
import MarkdownRender from '../components/MarkdownRender';
2023-05-21 05:48:11 +00:00
import { ToolTipButton } from '../components/ToolTipButton';
2023-06-15 16:12:13 +00:00
import { ArrowCircleUp28Regular, Delete28Regular, RecordStop28Regular, Save28Regular } from '@fluentui/react-icons';
2023-05-21 05:48:11 +00:00
import { CopyButton } from '../components/CopyButton';
import { ReadButton } from '../components/ReadButton';
import { toast } from 'react-toastify';
2023-05-24 13:27:23 +00:00
import { WorkHeader } from '../components/WorkHeader';
2023-06-15 14:55:38 +00:00
import { DialogButton } from '../components/DialogButton';
2023-06-15 16:12:13 +00:00
import { OpenFileFolder, OpenSaveFileDialog } from '../../wailsjs/go/backend_golang/App';
import { toastWithButton } from '../utils';
2023-05-19 06:22:37 +00:00
2023-05-20 08:07:08 +00:00
export const userName = 'M E';
export const botName = 'A I';
2023-05-19 06:22:37 +00:00
2023-05-20 08:07:08 +00:00
export enum MessageType {
2023-05-19 06:22:37 +00:00
Normal,
Error
}
2023-05-20 08:07:08 +00:00
export type Side = 'left' | 'right'
2023-05-19 06:22:37 +00:00
2023-05-20 08:07:08 +00:00
export type Color = 'neutral' | 'brand' | 'colorful'
2023-05-19 06:22:37 +00:00
2023-05-20 08:07:08 +00:00
export type MessageItem = {
2023-05-19 06:22:37 +00:00
sender: string,
type: MessageType,
color: Color,
avatarImg?: string,
time: string,
content: string,
side: Side,
done: boolean
}
2023-06-15 16:12:13 +00:00
export type Conversation = {
2023-05-19 06:22:37 +00:00
[uuid: string]: MessageItem
}
2023-06-14 12:06:19 +00:00
let chatSseController: AbortController | null = null;
2023-05-19 06:22:37 +00:00
const ChatPanel: FC = observer(() => {
2023-05-21 05:48:11 +00:00
const { t } = useTranslation();
2023-05-19 06:22:37 +00:00
const bodyRef = useRef<HTMLDivElement>(null);
2023-05-19 07:40:17 +00:00
const inputRef = useRef<HTMLTextAreaElement>(null);
2023-05-19 06:22:37 +00:00
const port = commonStore.getCurrentModelConfig().apiParameters.apiPort;
2023-05-19 12:10:30 +00:00
let lastMessageId: string;
let generating: boolean = false;
2023-06-15 16:12:13 +00:00
if (commonStore.conversationOrder.length > 0) {
lastMessageId = commonStore.conversationOrder[commonStore.conversationOrder.length - 1];
const lastMessage = commonStore.conversation[lastMessageId];
2023-05-19 12:10:30 +00:00
if (lastMessage.sender === botName)
generating = !lastMessage.done;
}
2023-05-19 06:22:37 +00:00
2023-05-19 07:40:17 +00:00
useEffect(() => {
if (inputRef.current)
inputRef.current.style.maxHeight = '16rem';
2023-05-23 04:24:39 +00:00
scrollToBottom();
2023-05-19 07:40:17 +00:00
}, []);
2023-05-20 08:07:08 +00:00
useEffect(() => {
2023-06-15 16:12:13 +00:00
if (commonStore.conversationOrder.length === 0) {
commonStore.setConversationOrder(['welcome']);
commonStore.setConversation({
2023-05-20 08:07:08 +00:00
'welcome': {
sender: botName,
type: MessageType.Normal,
color: 'colorful',
avatarImg: logo,
time: new Date().toISOString(),
content: t('Hello! I\'m RWKV, an open-source and commercially available large language model.'),
side: 'left',
done: true
}
});
}
}, []);
2023-05-19 06:22:37 +00:00
const scrollToBottom = () => {
if (bodyRef.current)
bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
};
2023-05-19 12:10:30 +00:00
const handleKeyDownOrClick = (e: any) => {
e.stopPropagation();
if (e.type === 'click' || (e.keyCode === 13 && !e.shiftKey)) {
e.preventDefault();
2023-05-24 16:51:45 +00:00
if (commonStore.status.status === ModelStatus.Offline) {
2023-05-21 05:48:11 +00:00
toast(t('Please click the button in the top right corner to start the model'), { type: 'warning' });
2023-05-20 02:38:35 +00:00
return;
}
2023-06-14 12:26:04 +00:00
if (!commonStore.currentInput) return;
onSubmit(commonStore.currentInput);
commonStore.setCurrentInput('');
2023-05-19 12:10:30 +00:00
}
};
const onSubmit = (message: string) => {
const newId = uuid();
2023-06-15 16:12:13 +00:00
commonStore.conversation[newId] = {
2023-05-19 12:10:30 +00:00
sender: userName,
type: MessageType.Normal,
color: 'brand',
time: new Date().toISOString(),
content: message,
side: 'right',
done: true
};
2023-06-15 16:12:13 +00:00
commonStore.setConversation(commonStore.conversation);
commonStore.conversationOrder.push(newId);
commonStore.setConversationOrder(commonStore.conversationOrder);
2023-05-19 12:10:30 +00:00
const records: Record[] = [];
2023-06-15 16:12:13 +00:00
commonStore.conversationOrder.forEach((uuid, index) => {
const messageItem = commonStore.conversation[uuid];
if (messageItem.done && messageItem.type === MessageType.Normal && messageItem.sender === botName) {
2023-05-19 12:10:30 +00:00
if (index > 0) {
2023-06-15 16:12:13 +00:00
const questionId = commonStore.conversationOrder[index - 1];
const question = commonStore.conversation[questionId];
2023-05-19 12:10:30 +00:00
if (question.done && question.type === MessageType.Normal && question.sender === userName) {
2023-06-15 16:12:13 +00:00
records.push({ question: question.content, answer: messageItem.content });
2023-05-19 06:22:37 +00:00
}
}
2023-05-19 12:10:30 +00:00
}
});
const messages = getConversationPairs(records, false);
2023-05-21 05:48:11 +00:00
(messages as ConversationPair[]).push({ role: 'user', content: message });
2023-05-19 12:10:30 +00:00
const answerId = uuid();
2023-06-15 16:12:13 +00:00
commonStore.conversation[answerId] = {
2023-05-19 12:10:30 +00:00
sender: botName,
type: MessageType.Normal,
color: 'colorful',
avatarImg: logo,
time: new Date().toISOString(),
content: '',
side: 'left',
done: false
};
2023-06-15 16:12:13 +00:00
commonStore.setConversation(commonStore.conversation);
commonStore.conversationOrder.push(answerId);
commonStore.setConversationOrder(commonStore.conversationOrder);
2023-05-19 12:10:30 +00:00
setTimeout(scrollToBottom);
let answer = '';
2023-06-14 12:06:19 +00:00
chatSseController = new AbortController();
2023-05-19 12:10:30 +00:00
fetchEventSource(`http://127.0.0.1:${port}/chat/completions`, // https://api.openai.com/v1/chat/completions || http://127.0.0.1:${port}/chat/completions
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer sk-`
},
body: JSON.stringify({
messages,
stream: true,
model: 'gpt-3.5-turbo'
}),
2023-06-14 12:06:19 +00:00
signal: chatSseController?.signal,
2023-05-19 12:10:30 +00:00
onmessage(e) {
console.log('sse message', e);
scrollToBottom();
if (e.data === '[DONE]') {
2023-06-15 16:12:13 +00:00
commonStore.conversation[answerId].done = true;
commonStore.conversation[answerId].content = commonStore.conversation[answerId].content.trim();
commonStore.setConversation(commonStore.conversation);
commonStore.setConversationOrder([...commonStore.conversationOrder]);
2023-05-19 12:10:30 +00:00
return;
2023-05-19 06:22:37 +00:00
}
2023-05-19 12:10:30 +00:00
let data;
try {
data = JSON.parse(e.data);
} catch (error) {
console.debug('json error', error);
return;
}
if (data.choices && Array.isArray(data.choices) && data.choices.length > 0) {
answer += data.choices[0]?.delta?.content || '';
2023-06-15 16:12:13 +00:00
commonStore.conversation[answerId].content = answer;
commonStore.setConversation(commonStore.conversation);
commonStore.setConversationOrder([...commonStore.conversationOrder]);
2023-05-19 12:10:30 +00:00
}
},
onclose() {
console.log('Connection closed');
},
onerror(err) {
2023-06-15 16:12:13 +00:00
commonStore.conversation[answerId].type = MessageType.Error;
commonStore.conversation[answerId].done = true;
commonStore.setConversation(commonStore.conversation);
commonStore.setConversationOrder([...commonStore.conversationOrder]);
2023-05-19 12:10:30 +00:00
throw err;
}
});
2023-05-19 06:22:37 +00:00
};
2023-05-05 15:23:34 +00:00
2023-05-19 02:08:28 +00:00
return (
2023-05-19 06:22:37 +00:00
<div className="flex flex-col w-full grow gap-4 pt-4 overflow-hidden">
<div ref={bodyRef} className="grow overflow-y-scroll overflow-x-hidden pr-2">
2023-06-15 16:12:13 +00:00
{commonStore.conversationOrder.map((uuid, index) => {
const messageItem = commonStore.conversation[uuid];
2023-05-19 06:22:37 +00:00
return <div
key={uuid}
className={classnames(
2023-05-19 07:40:17 +00:00
'flex gap-2 mb-2 overflow-hidden',
2023-06-15 16:12:13 +00:00
messageItem.side === 'left' ? 'flex-row' : 'flex-row-reverse'
2023-05-19 06:22:37 +00:00
)}
2023-05-19 12:55:12 +00:00
onMouseEnter={() => {
const utils = document.getElementById('utils-' + uuid);
if (utils) utils.classList.remove('invisible');
}}
onMouseLeave={() => {
const utils = document.getElementById('utils-' + uuid);
if (utils) utils.classList.add('invisible');
}}
2023-05-19 06:22:37 +00:00
>
<Avatar
2023-06-15 16:12:13 +00:00
color={messageItem.color}
name={messageItem.sender}
image={messageItem.avatarImg ? { src: messageItem.avatarImg } : undefined}
2023-05-19 06:22:37 +00:00
/>
<div
className={classnames(
2023-05-19 07:40:17 +00:00
'p-2 rounded-lg overflow-hidden',
2023-06-15 16:12:13 +00:00
messageItem.side === 'left' ? 'bg-gray-200' : 'bg-blue-500',
messageItem.side === 'left' ? 'text-gray-600' : 'text-white'
2023-05-19 06:22:37 +00:00
)}
>
2023-06-15 16:12:13 +00:00
<MarkdownRender>{messageItem.content}</MarkdownRender>
2023-05-19 06:22:37 +00:00
</div>
2023-05-19 12:55:12 +00:00
<div className="flex flex-col gap-1 items-start">
2023-05-21 05:48:11 +00:00
<div className="grow" />
2023-06-15 16:12:13 +00:00
{(messageItem.type === MessageType.Error || !messageItem.done) &&
2023-05-19 12:55:12 +00:00
<PresenceBadge size="extra-small" status={
2023-06-15 16:12:13 +00:00
messageItem.type === MessageType.Error ? 'busy' : 'away'
2023-05-21 05:48:11 +00:00
} />
2023-05-19 12:55:12 +00:00
}
<div className="flex invisible" id={'utils-' + uuid}>
2023-06-15 16:12:13 +00:00
<ReadButton content={messageItem.content} />
<CopyButton content={messageItem.content} />
2023-05-19 12:55:12 +00:00
</div>
</div>
2023-05-19 06:22:37 +00:00
</div>;
})}
</div>
2023-05-19 12:10:30 +00:00
<div className="flex items-end gap-2">
2023-06-15 14:55:38 +00:00
<DialogButton tooltip={t('Clear')}
2023-05-21 05:48:11 +00:00
icon={<Delete28Regular />}
2023-06-15 14:55:38 +00:00
size="large" shape="circular" appearance="subtle" title={t('Clear')}
contentText={t('Are you sure you want to clear the conversation? It cannot be undone.')}
onConfirm={() => {
2023-05-21 05:48:11 +00:00
if (generating)
2023-06-14 12:06:19 +00:00
chatSseController?.abort();
2023-06-15 16:12:13 +00:00
commonStore.setConversation({});
commonStore.setConversationOrder([]);
2023-06-15 14:55:38 +00:00
}} />
2023-05-19 12:10:30 +00:00
<Textarea
ref={inputRef}
className="grow"
resize="vertical"
placeholder={t('Type your message here')!}
2023-06-14 12:26:04 +00:00
value={commonStore.currentInput}
onChange={(e) => commonStore.setCurrentInput(e.target.value)}
2023-05-19 12:10:30 +00:00
onKeyDown={handleKeyDownOrClick}
/>
<ToolTipButton desc={generating ? t('Stop') : t('Send')}
2023-05-21 05:48:11 +00:00
icon={generating ? <RecordStop28Regular /> : <ArrowCircleUp28Regular />}
size="large" shape="circular" appearance="subtle"
onClick={(e) => {
if (generating) {
2023-06-14 12:06:19 +00:00
chatSseController?.abort();
2023-05-21 05:48:11 +00:00
if (lastMessageId) {
2023-06-15 16:12:13 +00:00
commonStore.conversation[lastMessageId].type = MessageType.Error;
commonStore.conversation[lastMessageId].done = true;
commonStore.setConversation(commonStore.conversation);
commonStore.setConversationOrder([...commonStore.conversationOrder]);
2023-05-21 05:48:11 +00:00
}
} else {
handleKeyDownOrClick(e);
}
}} />
2023-06-15 16:12:13 +00:00
<ToolTipButton desc={t('Save')}
icon={<Save28Regular />}
size="large" shape="circular" appearance="subtle"
onClick={() => {
let savedContent: string = '';
commonStore.conversationOrder.forEach((uuid) => {
const messageItem = commonStore.conversation[uuid];
savedContent += `**${messageItem.sender}**\n - ${new Date(messageItem.time).toLocaleString()}\n\n${messageItem.content}\n\n`;
});
OpenSaveFileDialog('*.md', 'conversation.md', savedContent).then((path) => {
if (path)
toastWithButton(t('Conversation Saved'), t('Open'), () => {
OpenFileFolder(path, false);
});
}).catch(e => {
toast(t('Error') + ' - ' + e.message || e, { type: 'error', autoClose: 2500 });
});
}} />
2023-05-19 06:22:37 +00:00
</div>
</div>
2023-05-19 02:08:28 +00:00
);
2023-05-19 06:22:37 +00:00
});
2023-05-19 02:08:28 +00:00
export const Chat: FC = observer(() => {
2023-05-05 15:23:34 +00:00
return (
2023-05-19 02:08:28 +00:00
<div className="flex flex-col gap-1 p-2 h-full overflow-hidden">
2023-05-24 13:27:23 +00:00
<WorkHeader />
2023-05-21 05:48:11 +00:00
<ChatPanel />
2023-05-19 02:08:28 +00:00
</div>
2023-05-05 15:23:34 +00:00
);
2023-05-19 02:08:28 +00:00
});