跳至主要內容

從 AI SDK v4 遷移至 v5

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

如需所有 AI SDK 核心的破壞性變更、套件更新與 API 變更,請依照官方的 AI SDK v5 遷移指南操作。

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

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

Memory 與儲存空間
「Memory 與儲存空間」的直接連結

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 支援,確保整個應用程式的型別安全。