Skip to content

Methods writeSource and writeMessageAnnotation do not update data of sources and messages[i].annotations in StreamTextOnFinishCallback #6433

Open
@carlosleandr

Description

@carlosleandr

Description

I'm using the methods writeSource and writeMessageAnnotation in onChunk and expected that by the end of transmission, this data would be present in onFinish, but it's not. Is this intentional?

On frontend, useChat hook correctly receives these sources and annotations and adds them to the messages, as theoretically should happen at the end of transmission on backend.

Screenshot from browser console:
Image

My code:

return createDataStreamResponse({
    execute: (dataStream) => {
        const result = streamText({
            model: openai('gpt-4'),
            system: process.env.DEFAULT_PROMPT,
            messages,
            tools: { getWeather },
            experimental_transform: smoothStream({ chunking: 'word' }),
            experimental_generateMessageId: generateUUID,
            onChunk: ({ chunk }) => {
                if (
                    urlPattern &&
                    chunk.type === 'text-delta' &&
                    chunk.textDelta.length >= 30
                ) {
                    const url = urlPattern.exec(chunk.textDelta)?.[0];
                    if (url) {
                        dataStream.writeSource({
                            id: url,
                            url,
                            title: urlTitles[url],
                            sourceType: 'url',
                        });
                        dataStream.writeMessageAnnotation({
                            id: url,
                            url,
                            title: urlTitles[url],
                            sourceType: 'url',
                        });
                    }
                }
            },
            onFinish: async ({ response: { messages }, sources }) => {
                // `sources` is empty
                // `messages[i].annotations` is undefined
                // `messages[i].parts[i].type==='source'` doesnt exist
            },
        });
        result.consumeStream();
        result.mergeIntoDataStream(dataStream, {
            sendReasoning: true,
            sendSources: true,
        });
    },
}

AI SDK Version

  • ai: 4.3.4
  • @ai-sdk/react: 1.2.8
  • @ai-sdk/openai: 1.3.10

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions