Convert useChat messages to ModelMessages for AI functions (API Reference)
The convertToModelMessages function is used to transform an array of UI messages from the useChat hook into an array of ModelMessage objects. These ModelMessage objects are compatible with AI core functions like streamText.
Optional configuration object. Provide tools to enable multi-modal tool responses, and convertDataPart to transform custom data parts into model-compatible content.
The convertToModelMessages function supports tools that can return multi-modal content. This is useful when tools need to return non-text content like images.
import { tool } from 'ai';
import { z } from 'zod';
const screenshotTool = tool({
inputSchema: z.object({}),
execute: async () => 'imgbase64',
toModelOutput: result => [{ type: 'image', data: result }],
});
const result = streamText({
model: "anthropic/claude-sonnet-5.5",
messages: convertToModelMessages(messages, {
tools: {
screenshot: screenshotTool,
},
}),
});
Tools can implement the optional toModelOutput method to transform their results into multi-modal content. The content is an array of content parts, where each part has a type (e.g., 'text', 'image') and corresponding data.
The convertToModelMessages function supports converting custom data parts attached to user messages. This is useful when users need to include additional context (URLs, code files, JSON configs) with their messages.
By default, data parts in user messages are filtered out during conversion. To include them, provide a convertDataPart callback that transforms data parts into text or file parts that the model can understand:
app/api/chat/route.ts
import { convertToModelMessages, streamText, UIMessage } from 'ai';
type CustomUIMessage = UIMessage<
never,
{
url: { url: string; title: string; content: string };
'code-file': { filename: string; code: string; language: string };
}
>;
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: "anthropic/claude-sonnet-5.5",
messages: convertToModelMessages<CustomUIMessage>(messages, {
convertDataPart: part => {
// Convert URL attachments to text
if (part.type === 'data-url') {
return {
type: 'text',
text: `[Reference: ${part.data.title}](${part.data.url})\n\n${part.data.content}`,
};
}
// Convert code file attachments
if (part.type === 'data-code-file') {
return {
type: 'text',
text: `\`\`\`${part.data.language}\n// ${part.data.filename}\n${part.data.code}\n\`\`\``,
};
}
// Other data parts are ignored
},
}),
});
return result.toUIMessageStreamResponse();
}