跳至主要內容

從 AI SDK v4 遷移至 v5

正在尋找整合文件?請參閱使用 AI SDK

關於所有 AI SDK 核心重大變更、套件更新及 API 變更,請依照官方的 AI SDK v5 遷移指南操作。

本指南只涵蓋遷移中與 Mastra 相關的部分。

  • 資料兼容性:以 v5 格式儲存的新資料,在你從 v5 降級至 v4 後將無法再使用
  • 備份建議:保留升級至 v5 前的資料庫備份

記憶體及儲存空間
記憶體及儲存空間 的直接連結

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'

如果你想直接從儲存資料庫擷取訊息,再轉換供 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 支援,確保整個應用程式的類型安全。