Skip to content

Accessing all messages on onFinish hook for saving chat history [useChat] #2013

Answered by jeremyphilemon
djam90 asked this question in Help
Discussion options

You must be logged in to vote

Here's the recommended way to store messages using useChat in the route handler.

Ideally, you save the current generation to the database on the server, that way you avoid experiencing redundant/duplicate saves on the client.

I'm also assuming you're saving the whole conversation during every generation, so the following should work:

@/app/api/chat/route.ts
import { openai } from '@ai-sdk/openai';
import { streamText, convertToCoreMessages } from 'ai';

export async function POST(req: Request) {
  const { id, messages } = await req.json();

  const result = await streamText({
    model: openai('gpt-4-turbo'),
    messages: convertToCoreMessages(messages),
    async onFinish({ text, toolCalls

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@thiagozf
Comment options

Answer selected by jeremyphilemon
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
5 participants