> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # 從 AI SDK v4 遷移至 v5 正在尋找整合文件?請參閱[使用 AI SDK](https://mastra.zisheng.pro/zh-HK/guides/build-your-ui/ai-sdk-ui)。 關於所有 AI SDK 核心重大變更、套件更新及 API 變更,請依照官方的 [AI SDK v5 遷移指南](https://v5.ai-sdk.dev/docs/migration-guides/migration-guide-5-0)操作。 本指南只涵蓋遷移中與 Mastra 相關的部分。 - **資料兼容性**:以 v5 格式儲存的新資料,在你從 v5 降級至 v4 後將無法再使用 - **備份建議**:保留升級至 v5 前的資料庫備份 ## 記憶體及儲存空間 Mastra 會透過內部的 `MessageList` 類別自動處理 AI SDK v4 資料。此類別負責格式轉換,包括從 v4 轉換至 v5。你不需要遷移資料庫。現有訊息會即時轉換,升級後仍可繼續使用。 ## 訊息格式轉換 如果需要在 AI SDK 與 Mastra 格式之間手動轉換訊息,請使用 `convertMessages()` 工具函數: ```typescript 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 的類型推斷 在 AI SDK v5 中配合 TypeScript 使用 Tool 時,Mastra 提供類型推斷輔助工具,確保 Tool 輸入及輸出的類型安全。 ### `InferUITool` `InferUITool` 類型輔助工具會推斷單一 Mastra Tool 的輸入及輸出類型: ```typescript 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 // This creates: // { // input: { location: string }; // output: { temperature: number; conditions: string }; // } ``` ### `InferUITools` `InferUITools` 類型輔助工具會推斷多個 Tool 的輸入及輸出類型: ```typescript 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 // 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 支援,確保整個應用程式的類型安全。