onFinish Callback is not working - AI SDK V5
Unanswered
Pacific anchoveta posted this in #help-forum
Pacific anchovetaOP
const streamContext = getStreamContext();
if (streamContext) {
return new Response(
await streamContext.resumableStream(streamId, () =>
stream
.toUIMessageStream({
newMessageId: crypto.randomUUID(),
onFinish: async ({ responseMessage }) => {
await saveMessages({
messages: [
{
...responseMessage,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
attachments: [],
chatId: id,
} as DBMessage,
],
});
},
sendStart: true,
sendFinish: true,
sendReasoning: true,
sendSources: true,
})
.pipeThrough(
new TransformStream({
transform(chunk, controller) {
if (chunk.type === "text") {
controller.enqueue(chunk.text);
}
},
}),
),
),
);
}
return createUIMessageStreamResponse({
stream: stream.toUIMessageStream({
sendFinish: true,
sendReasoning: true,
sendSources: true,
sendStart: true,
newMessageId: crypto.randomUUID(),
onFinish: async ({ responseMessage }) => {
await saveMessages({
messages: [
{
...responseMessage,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
attachments: [],
chatId: id,
} as DBMessage,
],
});
},
}),
});
const {
messages,
} = useChat({
onFinish: async (opts) => {
console.log(opts)
},
...
});
2 Replies
Pacific anchovetaOP
What's the skill issue here? Am I doing something wrong overall? Is there a better way to handle all this in V5? Also, why am I not getting the onFinish when I receive the response from the AI?
Please help 🙏