跳到主要内容

从 AI SDK v4 迁移到 v5

如需集成文档,请参阅使用 AI SDK

有关 AI SDK 核心的所有破坏性变更、包更新和 API 变更,请遵循官方 AI SDK v5 迁移指南

本指南仅介绍迁移中与 Mastra 相关的部分。

  • 数据兼容性:如果从 v5 降级到 v4,以 v5 格式存储的新数据将无法继续使用
  • 备份建议:保留升级到 v5 之前的数据库备份

Memory 和 Storage
Memory 和 Storage的直接链接

Mastra 使用内部 MessageList 类自动处理 AI SDK v4 数据,包括管理从 v4 到 v5 的格式转换。无需迁移数据库。现有消息会即时转换,并在升级后继续正常工作。

消息格式转换
消息格式转换的直接链接

如需在 AI SDK 与 Mastra 格式之间手动转换消息,请使用 convertMessages() 工具函数:

import { convertMessages } from '@mastra/core/agent'

// Convert AI SDK v4 messages to v5
const aiv5Messages = convertMessages(aiv4Messages).to('AIV5.UI')

// Convert Mastra messages to AI SDK v5
const aiv5Messages = convertMessages(mastraMessages).to('AIV5.Core')

// Supported output formats:
// 'Mastra.V2', 'AIV4.UI', 'AIV5.UI', 'AIV5.Core', 'AIV5.Model'

当你想直接从 Storage 数据库获取消息并将其转换为 AI SDK 可用的格式时,此工具函数很有用。

Tool 的类型推断
Tool 的类型推断的直接链接

在 AI SDK v5 中配合 TypeScript 使用 Tool 时,Mastra 提供了类型推断辅助类型,以确保 Tool 输入和输出的类型安全。

InferUITool
inferuitool的直接链接

InferUITool 类型辅助工具可推断单个 Mastra Tool 的输入和输出类型:

app/types.ts
import { InferUITool, createTool } from '@mastra/core/tools'
import { z } from 'zod'

const weatherTool = createTool({
id: 'get-weather',
description: 'Get the current weather',
inputSchema: z.object({
location: z.string().describe('The city and state'),
}),
outputSchema: z.object({
temperature: z.number(),
conditions: z.string(),
}),
execute: async inputData => {
return {
temperature: 72,
conditions: 'sunny',
}
},
})

// Infer the types from the tool
type WeatherUITool = InferUITool<typeof weatherTool>
// This creates:
// {
// input: { location: string };
// output: { temperature: number; conditions: string };
// }

InferUITools
inferuitools的直接链接

InferUITools 类型辅助工具可推断多个 Tool 的输入和输出类型:

app/mastra/tools.ts
import { InferUITools, createTool } from '@mastra/core/tools'
import { z } from 'zod'

// Using weatherTool from the previous example
const tools = {
weather: weatherTool,
calculator: createTool({
id: 'calculator',
description: 'Perform basic arithmetic',
inputSchema: z.object({
operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
a: z.number(),
b: z.number(),
}),
outputSchema: z.object({
result: z.number(),
}),
execute: async inputData => {
// implementation...
return { result: 0 }
},
}),
}

// Infer types from the tool set
export type MyUITools = InferUITools<typeof tools>
// This creates:
// {
// weather: { input: { location: string }; output: { temperature: number; conditions: string } };
// calculator: { input: { operation: "add" | "subtract" | "multiply" | "divide"; a: number; b: number }; output: { result: number } };
// }

将 Mastra Tool 与 AI SDK v5 UI 组件配合使用时,这些类型辅助工具可提供完整的 TypeScript 支持,确保整个应用中的类型安全。