Vercel AI SDK Save completion message to database
Unanswered
Sanderling posted this in #help-forum
SanderlingOP
I am using ai/rsc from here https://sdk.vercel.ai/docs/getting-started/nextjs-app-router#introducing-airsc
I have a simple form, a teaxt area and a button. My form action executes this handleSubmit function which calls the continueConversation server action
inside continueConversation function
After streaming the AI response, ideally I wanted to save it to the database.
inside
The completion message doesn't get saved because message is null inside saveLatestMessage function
I have a simple form, a teaxt area and a button. My form action executes this handleSubmit function which calls the continueConversation server action
const handleSubmit = async () => {
const newMessages: CoreMessage[] = [...messages, { content: input, role: 'user' }];
setMessages(newMessages);
setInput('');
const result = await continueConversation(newMessages, fileId);
for await (const content of readStreamableValue(result)) {
setMessages([
...newMessages,
{
role: 'assistant',
content: content as string,
},
]);
}
await saveLatestMessage(messages, fileId);
};inside continueConversation function
const result = await streamText({
model: openai('gpt-4-turbo'),
temperature: 0,
messages: ...
});
const stream = createStreamableValue(result.textStream)
return stream.valueAfter streaming the AI response, ideally I wanted to save it to the database.
await saveLatestMessage(messages, fileId);inside
saveLatestMessage function const message = messages.pop()
if (!message) {
console.log('null message')
return null;
}
await prisma.message.create({
data: {
text: message.content as string,
isUserMessage: message.role === 'user' ? true : false,
userId: userId,
fileId: fileId
},
});The completion message doesn't get saved because message is null inside saveLatestMessage function
3 Replies
SanderlingOP
handleSubmit
saveLastMessage
saveLastMessage
this is from continueConversation function
American Crow
The ai sdk got an event for that within the
https://sdk.vercel.ai/docs/ai-sdk-rsc/saving-and-restoring-states#saving-ai-state
createAI function called onSetAIState you can cal your prsima db directly fromt here:https://sdk.vercel.ai/docs/ai-sdk-rsc/saving-and-restoring-states#saving-ai-state