> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt
# toAISdkV4Messages()
将输入格式的消息转换为 AI SDK V4 UI 消息格式。此函数接受多种格式的消息(字符串、AI SDK V4/V5 消息、Mastra DB 消息等),并将其规范化为 AI SDK V4 `UIMessage` 格式,适合与 `useChat()` 等 AI SDK UI 组件配合使用。
## 使用示例
```typescript
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 (
{messages.map(message => (
{message.role}: {message.content}
))}
)
}
```
## 参数
**messages** (`MessageListInput`): 要转换的消息。可以是字符串、字符串数组、单个消息对象,或采用任意受支持格式的消息对象数组。
## 返回值
返回具有以下结构的 AI SDK V4 `UIMessage` 对象数组:
**id** (`string`): 消息的唯一标识符。
**role** (`'user' | 'assistant' | 'system'`): 消息发送者的 role。
**content** (`string`): 消息的文本内容。
**parts** (`UIMessagePart[]`): UI part 数组,包括文本、Tool 调用、文件、推理、来源和 step 标记。
**createdAt** (`Date`): 消息创建时间戳。
**toolInvocations** (`ToolInvocation[]`): assistant 消息的 Tool 调用数组。
**experimental\_attachments** (`Attachment[]`): 消息中的文件附件。
**metadata** (`Record`): 附加到消息的自定义 metadata。
## 示例
### 转换文本消息
```typescript
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 client 加载消息
```typescript
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)
```