From dfc73a1fb28bea836fa389585cb3e165ee857383 Mon Sep 17 00:00:00 2001 From: Ismail Pelaseyed Date: Mon, 24 Apr 2023 10:49:24 +0200 Subject: [PATCH] Refactor chat (#81) * Add `code blocks` to markdown * Refactor messages * Add autofocus to textarea --- app/api/v1/chatbots/[chatbotId]/route.js | 1 + components/chat/index.js | 5 +- components/chat/input.js | 15 ++- components/chat/message.js | 100 ++++++++++++++++ components/chat/output.js | 125 ++------------------ lib/chain.js | 2 +- lib/markdown.js | 7 ++ lib/prisma.js | 2 + lib/prompt-template.js | 15 ++- package-lock.json | 141 +++++++++++++++++++++++ package.json | 1 + 11 files changed, 291 insertions(+), 123 deletions(-) create mode 100644 components/chat/message.js create mode 100644 lib/markdown.js diff --git a/app/api/v1/chatbots/[chatbotId]/route.js b/app/api/v1/chatbots/[chatbotId]/route.js index 2020d2d..d5ed47c 100644 --- a/app/api/v1/chatbots/[chatbotId]/route.js +++ b/app/api/v1/chatbots/[chatbotId]/route.js @@ -32,6 +32,7 @@ export async function POST(request, { params }) { : undefined; const handleNewToken = async (token) => { + const match = /\r|\n/.exec(token); await writer.ready; await writer.write(encoder.encode(`data: ${token}\n\n`)); }; diff --git a/components/chat/index.js b/components/chat/index.js index 3f17d7a..aa06369 100644 --- a/components/chat/index.js +++ b/components/chat/index.js @@ -10,6 +10,7 @@ export default function Chat({ id, ...properties }) { const [messages, setMessages] = useState([]); const [newMessage, setNewMessage] = useState(); const [isSendingMessage, setIsSendingMessage] = useState(); + const decoder = new TextDecoder(); const onSubmit = useCallback( async (values) => { @@ -35,8 +36,8 @@ export default function Chat({ id, ...properties }) { message: values, }), async onmessage(event) { - if (event.data !== "" && event.data !== "CLOSE") { - message += event.data; + if (event.data !== "CLOSE") { + message += event.data === "" ? `${event.data} \n` : event.data; setNewMessage(message); } diff --git a/components/chat/input.js b/components/chat/input.js index ddbcb75..9bacaba 100644 --- a/components/chat/input.js +++ b/components/chat/input.js @@ -49,20 +49,33 @@ export default function ChatInput({ isLoading, onSubmit, ...properties }) { }; }, []); + useEffect(() => { + const ref = textareaReference?.current; + + if (!isLoading) { + ref.focus(); + } + }, [isLoading]); + return (