From 124efca9a1cb3d42e968ae6dcdb68ed1483ff478 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Tue, 24 Sep 2024 20:11:50 +0530 Subject: [PATCH] Save to db on final ai state update (#429) Co-authored-by: jb-dev1 <10735400+jb-dev1@users.noreply.github.com> --- lib/chat/actions.tsx | 45 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/lib/chat/actions.tsx b/lib/chat/actions.tsx index ca6de3d..0aa4313 100644 --- a/lib/chat/actions.tsx +++ b/lib/chat/actions.tsx @@ -132,17 +132,17 @@ async function submitUserMessage(content: string) { system: `\ You are a stock trading conversation bot and you can help users buy stocks, step by step. You and the user can discuss stock prices and the user can adjust the amount of stocks they want to buy, or place an order, in the UI. - + Messages inside [] means that it's a UI element or a user event. For example: - "[Price of AAPL = 100]" means that an interface of the stock price of AAPL is shown to the user. - "[User has changed the amount of AAPL to 10]" means that the user has changed the amount of AAPL to 10 in the UI. - + If the user requests purchasing a stock, call \`show_stock_purchase_ui\` to show the purchase UI. If the user just wants the price, call \`show_stock_price\` to show the price. If you want to show trending stocks, call \`list_stocks\`. If you want to show events, call \`get_events\`. If the user wants to sell stock, or complete another impossible task, respond that you are a demo and cannot do that. - + Besides that, you can also chat with users and do some calculations if needed.`, messages: [ ...aiState.get().messages.map((message: any) => ({ @@ -517,34 +517,33 @@ export const AI = createAI({ return } }, - onSetAIState: async ({ state }) => { + onSetAIState: async ({ state, done }) => { 'use server' + if (!done) return + const session = await auth() + if (!session || !session.user) return - if (session && session.user) { - const { chatId, messages } = state + const { chatId, messages } = state - const createdAt = new Date() - const userId = session.user.id as string - const path = `/chat/${chatId}` + const createdAt = new Date() + const userId = session.user.id as string + const path = `/chat/${chatId}` - const firstMessageContent = messages[0].content as string - const title = firstMessageContent.substring(0, 100) + const firstMessageContent = messages[0].content as string + const title = firstMessageContent.substring(0, 100) - const chat: Chat = { - id: chatId, - title, - userId, - createdAt, - messages, - path - } - - await saveChat(chat) - } else { - return + const chat: Chat = { + id: chatId, + title, + userId, + createdAt, + messages, + path } + + await saveChat(chat) } })