Send `data` or custom fields from `streamText` to `useChat` similar to `annotations`
Feature Description
It would be awesome if we had a similar mechanism to message annotations but specifically for arbitrary data such as the model used to generate a response, the name/icon/id of the assistant used (not OpenAI assistants, just a custom one if your platform uses them) or the token usages. I am currently using annotations for this use case, but this feels like an antipattern - more in the "additional context" section of this issue.
On the server, you would instantiate a StreamData object and when you want to add/modify data that gets streamed back to the client, you call a method like...
const data = new StreamData();
data.appendMessageData({ data: { some: "json" }})
...then on the client via useChat you would intercept the data with...
const {
// ...
} = useChat({
// ...
onFinish: async (message) => {
const messageData = message.data
console.log('Message Data', message.data) // 3.3.x currently always prints undefined
},
});
....and you could render it like this:
return (
<div>
messages.map(message => (
<div>
<span>{message.role}</span>
<span>{message.content}</span>
{message.data?.model && <span>Model: {message.data.model}</span>}
</div>
)
</div>
)
Use Case
Feature would be useful in cases where message-level metadata unrelated to RAG citations or annotations needs to be streamed back to the client, such as the model used or the assistant used, as described above in the feature description.
For example, we have a very rudimental, custom LLM router on our server to use a "fallback" LLM in cases where the user's requested LLM is not available (rate limit, service down , connection errors, etc). As a result, the server needs to be able to communicate back to the client what LLM it actually used, and not which one was requested from the client side, since the two may be different.
Additional context
Our application requires storing some custom fields on each message, like:
- the model used to generate it
- details about the assistant the user sent the chat to (this is our own custom implementation of assistants, not to be confused with OpenAI assistants)
- various other fields like token usage.
Some of these don't need to be rendered client side (like token usage) but some do - like details about the assistant (so we can render the assistant's name and icon).
Currently, we are able to send arbitrary data to the server with no issues. We're using the append method provided by the useChat hook, and sending the data via the data attribute of Message.
append({
id: generateId(),
role: "user" as RoleType,
content: input,
createdAt: new Date(),
experimental_attachments: attachedFiles,
data: {
model: 'gpt-4o',
// ...
}
});
Then, we can grab the data from the last message server-side and customize the response based on these data (using a different model or prompt, etc)
However, there's no way for us to receive arbitrary data from the server on a per-message basis.
I am aware of the StreamData.append() method. However, since calling that adds to a global data object, trying to use for our per-message use case seems hacky and unstable; we'd need to link the data object up with the message via some identifier, and to add the fields to the appropriate messages so we can render the fields would require modifying state an extra time.
Currently, as a workaround, we're using annotations:
StreamData.appendMessageAnnotation({
data: {
model: "gpt-4o",
// ...
}
})
I'm not a huge fan of this either. I can't find much in the docs or in the repo about how annotations are supposed to be used, but from what I can gather and from my assumptions, these are supposed to be used for citing documents retrieved during a RAG chain, not for arbitrary or custom data. So it seems like an antipattern to use them for this case.
Here are some related items:
- #688
- #585
- #1180
Do the stream data message annotations not work? https://sdk.vercel.ai/docs/ai-sdk-ui/streaming-data
Do the stream data message annotations not work? https://sdk.vercel.ai/docs/ai-sdk-ui/streaming-data
@lgrammel, it seems like the requirements align closely with the ones i shared in this discussion.
To clarify, when using streaming data with StreamingData in useChat, there are currently two main ways to handle appending data:
At a global level, by using StreamingData.append, which appends data for whole chat. At a message level, but only for messages with role='assistant', by using StreamingData.appendMessageAnnotation. However, it appears there is no direct method to append annotations at the message level specifically for role='user'. This would be helpful for enhancing user-driven message interactivity and data tracking.
@lgrammel I apologize for the interruption again. As mentioned earlier, I'm working to simplify the transfer of user attachments between frontend and backend by customizing the convertToCoreMessages function to read experimental_attachments.
However, I noticed that in the latest AI version 3.4.29, convertToCoreMessages has been marked as deprecated.
With the above requirement in mind, I reviewed ai-sdk-preview-internal-knowledge-base in vercel_lab and observed that, to streamline the attachment message flow without automatically sending attachments to a provider(which now by default as my understanding), the example uses experimental_providerMetadata to transfer file information for reading and processing in middleware.
May I ask for your advice on whether this approach represents the best short-term practice, given the constraint of not upgrading for enhancements?
`const { id, messages, selectedFilePathnames } = await request.json();
const session = await auth();
if (!session) { return new Response("Unauthorized", { status: 401 }); }
const result = await streamText({ model: customModel, system: "you are a friendly assistant! keep your responses concise and helpful.", messages: convertToCoreMessages(messages), experimental_providerMetadata: { files: { selection: selectedFilePathnames, }, },`
I am also trying to upload files from the UI but bypassing the provider. Currently I can send data separately through the body option in handleSubmit.
The data is retrievable from the endpoint and it can be stored in the db, but there is no way of passing it to the UIMessage once handleSubmit is called.
Is there an alternative way of inserting more fields in the UIMessages that are appended to the chat via handleSubmit?
ai sdk 5 supports typed, custom data parts and message metadata.
Identify issue type
Identified as Feature
Confidence: High
Rationale
This is a request for new per-message custom data and metadata support, not a concrete failure of existing promised behavior.
Evidence
- The issue requests a message-level mechanism for streaming arbitrary custom data from
streamTexttouseChat. - Existing options (
StreamData.appendand message annotations) are described as insufficient or semantically inappropriate, rather than broken against documented behavior. - A maintainer later states that AI SDK 5 supports typed custom data parts and message metadata, indicating the requested capability was added.