toAISdkV4Messages()
将来自各种输入格式的消息转换为 AI SDK V4 UI 消息格式。此功能接受多种格式的消息(字符串、AI SDK V4/V5 消息、Mastra 数据库消息等),并将其规范化为适用于 AI SDK UI 组件(如 useChat() )的 AI SDK V4 UIMessage 格式。
🌐 Converts messages from various input formats to AI SDK V4 UI message format. This function accepts messages in multiple formats (strings, AI SDK V4/V5 messages, Mastra DB messages, etc.) and normalizes them to the AI SDK V4 UIMessage format, which is suitable for use with AI SDK UI components like useChat().
使用示例Direct link to 使用示例
🌐 Usage example
app/chat/page.tsx
import { toAISdkV4Messages } from "@mastra/ai-sdk";
import { useChat } from "ai/react"; // AI SDK V4
// Stored messages from your database, memory or API
const storedMessages = [
{ id: "1", role: "user", parts: [{ type: "text", text: "Hello" }] },
{ id: "2", role: "assistant", parts: [{ type: "text", text: "Hi there!" }] }
];
export default function Chat() {
const { messages } = useChat({
initialMessages: toAISdkV4Messages(storedMessages)
});
return (
<div>
{messages.map((message) => (
<div key={message.id}>
{message.role}: {message.content}
</div>
))}
</div>
);
}
参数Direct link to 参数
🌐 Parameters
messages:
MessageListInput
Messages to convert. Can be a string, array of strings, a single message object, or an array of message objects in any supported format.
返回Direct link to 返回
🌐 Returns
返回一个包含 AI SDK V4 UIMessage 对象的数组,结构如下:
🌐 Returns an array of AI SDK V4 UIMessage objects with the following structure:
id:
string
Unique message identifier.
role:
'user' | 'assistant' | 'system'
The role of the message sender.
content:
string
Text content of the message.
parts:
UIMessagePart[]
Array of UI parts including text, tool-invocation, file, reasoning, source, and step markers.
createdAt:
Date
Message creation timestamp.
toolInvocations?:
ToolInvocation[]
Array of tool invocations for assistant messages.
experimental_attachments?:
Attachment[]
File attachments on the message.
metadata?:
Record<string, unknown>
Custom metadata attached to the message.
示例Direct link to 示例
🌐 Examples
转换简单的文本消息Direct link to 转换简单的文本消息
🌐 Converting simple text messages
import { toAISdkV4Messages } from "@mastra/ai-sdk";
const messages = toAISdkV4Messages(["Hello", "How can I help you today?"]);
// Returns array of UIMessage objects with user role and content string
正在使用 Mastra 客户端加载消息Direct link to 正在使用 Mastra 客户端加载消息
🌐 Loading messages with Mastra client
import { MastraClient } from "@mastra/client-js";
import { toAISdkV4Messages } from "@mastra/ai-sdk";
const client = new MastraClient();
const { messages } = await client.listThreadMessages("thread-id", { agentId: "myAgent" });
const uiMessages = toAISdkV4Messages(messages);