Adapt chat input for text streaming
A server route receives messages from a useChat client and needs to call streamText.
AI Tools · Function
Converts useChat UI messages into CoreMessage objects suitable for AI Core functions such as streamText. The documentation warns that current SDK versions perform this conversion automatically.
The function accepts UI messages produced by useChat and transforms them into CoreMessage objects. Those converted messages can then be supplied to AI Core operations such as streamText; an optional tools configuration enables multimodal tool responses.
convertToCoreMessages(messages: Message[], options?: { tools?: ToolSet }): CoreMessage[]| Name | Type | Description |
|---|---|---|
messages | Message[] | UI messages from the useChat hook to convert. |
options | { tools?: ToolSet } | Optional configuration; provide tools to enable multimodal tool responses. |
CoreMessage[] — an array of CoreMessage objects.
import { openai } from '@ai-sdk/openai';
import { convertToCoreMessages, streamText } from 'ai';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-4o'),
messages: convertToCoreMessages(messages),
});
return result.toDataStreamResponse();
}Converts incoming useChat messages before passing them to streamText.
A server route receives messages from a useChat client and needs to call streamText.
A tool returns an image or another non-text result.
Provider-specific message handling requires the CoreMessage representation.
It converts an array of UI messages from useChat into CoreMessage objects. The resulting array is compatible with AI Core functions such as streamText.
Follow-up: What optional configuration does it accept? It accepts an options object with tools, which enables multimodal tool responses.
The messages parameter is a Message[] containing UI messages from useChat. The function returns an array of CoreMessage objects.
Follow-up: Why might the conversion be unnecessary today? The SDK now automatically converts incoming messages to CoreMessage format.
The function can support tools that return multimodal content. This is useful when a tool needs to return non-text data, such as an image.
Follow-up: How would you use it in a route? Read messages from the request, convert them, pass them to streamText, and return the resulting data stream.
CoreMessagestreamTextuseChatToolSet