From eddfd996364eb98033dd505a5065a7261d4f48a4 Mon Sep 17 00:00:00 2001 From: Niek van der Maas Date: Mon, 6 Mar 2023 16:46:45 +0100 Subject: [PATCH] Added chat name suggestion function --- src/lib/Chat.svelte | 74 +++++++++++++++++++++++++++++++++------------ 1 file changed, 55 insertions(+), 19 deletions(-) diff --git a/src/lib/Chat.svelte b/src/lib/Chat.svelte index 9b8ba54..05b733c 100644 --- a/src/lib/Chat.svelte +++ b/src/lib/Chat.svelte @@ -30,22 +30,10 @@ breaks: true, }; - const send = async () => { - // Compose the input message - const inputMessage: Message = { role: "user", content: input.value }; - addMessage(chatId, inputMessage); - - // Clear the input value - input.value = ""; - - // Resize back to auto - input.style.height = "auto"; - - // Show updating bar - updating = true; - + const sendRequest = async (messages: Message[]): Promise => { // Send API request /* + // Not working yet: a way to get the response as a stream await fetchEventSource("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { @@ -71,6 +59,8 @@ }, }); */ + // Show updating bar + updating = true; const response: Response = await ( await fetch("https://api.openai.com/v1/chat/completions", { @@ -82,7 +72,7 @@ body: JSON.stringify({ model: "gpt-3.5-turbo", // Submit only the role and content of the messages, provide the previous messages as well for context - messages: chat.messages.map((message): Message => { + messages: messages.map((message): Message => { const { role, content } = message; return { role, content }; }), @@ -96,11 +86,25 @@ }) ).json(); - console.log(response); - // Hide updating bar updating = false; + return response; + }; + + const submitForm = async (): Promise => { + // Compose the input message + const inputMessage: Message = { role: "user", content: input.value }; + addMessage(chatId, inputMessage); + + // Clear the input value + input.value = ""; + + // Resize back to single line height + input.style.height = "auto"; + + const response = await sendRequest(chat.messages); + if (response.error) { addMessage(chatId, { role: "system", @@ -113,6 +117,29 @@ }); } }; + + const suggestName = async (): Promise => { + const suggestMessage: Message = { + role: "user", + content: "Can you give me a 5 word summary of this conversation's topic?", + }; + addMessage(chatId, suggestMessage); + + const response = await sendRequest(chat.messages); + + if (response.error) { + addMessage(chatId, { + role: "system", + content: `Error: ${response.error.message}`, + }); + } else { + response.choices.map((choice) => { + choice.message.usage = response.usage; + addMessage(chatId, choice.message); + chat.name = choice.message.content; + }); + } + };