页面简介
Learn how to migrate your persisted messages and chat data from AI SDK 4.x to 5.0.
正文摘录
Migration GuidesMenuMigrate Your Data to AI SDK 5.0Copy for LLMView MarkdownAsk AI about this pageAI SDK 5.0 introduces changes to the message structure and persistence patterns. Unlike code migrations that can often be automated with codemods, data migration depends on your specific persistence approach, database schema, and application requirements. This guide helps you get your application working with AI SDK 5.0 first using a runtime conversion layer. This allows you to update your app immediately without database migrations blocking you. You can then migrate your data schema at your own pace. Recommended Migration Process Follow this two-phase approach for a safe migration: Phase 1: Get Your App Working (Runtime Conversion) Goal: Update your application to AI SDK 5.0 without touching your database. Update dependencies (install v4 types alongside v5) Add conversion functions to transform between v4 and v5 message formats Update data fetching logic to convert messages when reading from the database Update the rest of your application code to AI SDK 5.0 (see the main migration guide) Your database schema remains unchanged during Phase 1. You're only adding a conversion layer that transforms messages at runtime. Timeline: Can be completed in hours or days. Phase 2: Migrate to V5 Schema (Recommended) Goal: Migrate your data to a v5-compatible schema, eliminating the runtime conversion overhead. While Phase 1 gets you working immediately, migrate your schema soon after completing Phase 1. This phase uses a side-by-side migration approach with an equivalent v5 schema: Create messages_v5 table alongside existing messages table Start dual-writing to both tables (with conversion) Run a background migration to convert existing messages Switch reads to the v5 schema Remove conversion from your route handlers Remove dual-write (write only to v5) Drop old tables Timeline: Do this soon after Phase 1. Why this matters: Removes runtime conversion overhead Eliminates technical debt early Type safety with v5 message format Easier to maintain and extend Understanding the Changes Before starting, understand the main persistence-related changes in AI SDK 5.0: AI SDK 4.0: content field for text reasoning as a top-level property toolInvocations as a top-level property parts (optional) ordered array AI SDK 5.0: parts array is the single source of truth content is removed (deprecated) and accessed via a text part reasoning is removed and replaced with a reasoning part toolInvocations is removed and replaced with tool-${toolName} parts with input/output (renamed from args/result) data role removed (use data parts instead) Phase 1: Runtime Conversion Pattern This creates a conversion layer without making changes to your database schema. Step 1: Update Dependencies To get proper TypeScript types for your v4 messages, install the v4 package alongside v5 using npm aliases: package.json{ "dependencies": { "ai": "^5.0.0", "ai-legacy": "npm:ai@^4.3.2" } } Run: pnpm install Import v4 types for proper type safety: import type { Message as V4Message } from 'ai-legacy'; import type { UIMessage } from 'ai'; Step 2: Add Conversion Functions Create type guards to detect which message format you're working with, and build a conversion function that handles all v4 message types: import type { ToolInvocation, Message as V4Message, UIMessage as LegacyUIMessage, } from 'ai-legacy'; import type { ToolUIPart, UIMessage, UITools } from 'ai'; export type MyUIMessage = UIMessage<unknown, { custom: any }, UITools>; type V4Part = NonNullable<V4Message['parts']>[number]; type V5Part = MyUIMessage['parts'][number]; // Type definitions for V4 parts type V4ToolInvocationPart = Extract<V4Part, { type: 'tool-invocation' }>; type V4ReasoningPart = Extract<V4Part, { type: 'reasoning' }>; type V4SourcePart = Extract<V4Part, { type: 'source' }>; type V4FilePart = Extract<V4Part, { type: 'file' }>; // Type guards function isV4Message(msg: V4Message | MyUIMessage): msg is V4Message { return ( msg?.parts == null || 'toolInvocations' in msg || (msg?.parts?.some(p => p.type === 'tool-invocation') ?? false) || msg?.role === 'data' || ('reasoning' in msg && typeof msg.reasoning === 'string') || (msg?.parts?.some(p => 'args' in p || 'result' in p) ?? false) || (msg?.parts?.some(p => 'reasoning' in p && 'details' in p) ?? false) || (msg?.parts?.some( p => p.type === 'file' && 'mimeType' in p && 'data' in p, ) ?? false) ); } function isV4ToolInvocationPart(part: unknown): part is V4ToolInvocationPart { return ( typeof part === 'object' && part !== null && 'type' in part && part.type === 'tool-invocation' && 'toolInvocation' in part ); } function isV4ReasoningPart(part: unknown): part is V4ReasoningPart { return ( typeof part === 'object' && part !== null && 'type' in part && part.type === 'reasoning' && 'reasoning' in part ); } function isV4SourcePart(part: unknown): part is V4SourcePart { return ( typeof part === 'object' && part !== null && 'type' in part && part.type === 'source' && 'source' in part ); } function isV4FilePart(part: unknown): part is V4FilePart { return ( typeof part === 'object' && part !== null && 'type' in part && part.type === 'file' && 'mimeType' in part && 'data' in part ); } // State mapping const V4_TO_V5_STATE_MAP = { 'partial-call': 'input-streaming', call: 'input-available', result: 'output-available', } as const; function convertToolInvocationState( v4State: ToolInvocation['state'], ): 'input-streaming' | 'input-available' | 'output-available' { return V4_TO_V5_STATE_MAP[v4State] ?? 'output-available'; } // Tool conversion function convertV4ToolInvocationToV5ToolUIPart( toolInvocation: ToolInvocation, ): ToolUIPart { return { type: `tool-${toolInvocation.toolName}`, toolCallId: toolInvocation.toolCallId, input: toolInvocation.args, output: toolInvocation.state === 'result' ? toolInvocation.result : undefined, state: convertToolInvocationState(toolInvocation.state), }; } // Part converters function convertV4ToolInvocationPart(part: V4ToolInvocationPart): V5Part { return convertV4ToolInvocationToV5ToolUIPart(part.toolInvocation); } function convertV4ReasoningPart(part: V4ReasoningPart): V5Part { return { type: 'reasoning', text: part.reasoning }; } function convertV4SourcePart(part: V4SourcePart): V5Part { return { type: 'source-url', url: part.source.url, sourceId: part.source.id, title: part.source.title, }; } function convertV4FilePart(part: V4FilePart): V5Part { return { type: 'file', mediaType: part.mimeType, url: part.data, }; } function convertPart(part: V4Part | V5Part): V5Part { if (isV4ToolInvocationPart(part)) { return convertV4ToolInvocationPart(part); } if (isV4ReasoningPart(part)) { return convertV4ReasoningPart(part); } if (isV4SourcePart(part)) { return convertV4SourcePart(part); } if (isV4FilePart(part)) { return convertV4FilePart(part); } // Already V5 format return part; } // Message conversion function createBaseMessage( msg: V4Message | MyUIMessage, index: number, ): Pick<MyUIMessage, 'id' | 'role'> { return { id: msg.id || `msg-${index}`, role: msg.role === 'data' ? 'assistant' : msg.role, }; } function convertDataMessage(msg: V4Message, index: number): MyUIMessage { return { ...createBaseMessage(msg, index), parts: [ { type: 'data-custom', data: msg.data || msg.content, }, ], }; } function buildPartsFromTopLevelFields(msg: V4Message): MyUIMessage['parts'] { const parts: MyUIMessage['parts'] = []; if (msg.reasoning) { parts.push({ type: 'reasoning', text: msg.reasoning }); } if (msg.toolInvocations) { parts.push( ...msg.toolInvocations.map(convertV4ToolInvocationToV5ToolUIPart), ); } if (msg.content && typeof msg.content === 'string') { parts.push({ type: 'text', text: msg.content }); } return parts; } function convertPartsArray(parts: V4Part[]): MyUIMessage['parts'] { return parts.map(convertPart); } export function convertV4MessageToV5( msg: V4Message | MyUIMessage, index: number, ): MyUIMessage { if (!isV4Message(msg)) { return msg as MyUIMessage; } if (msg.role === 'data') { return convertDataMessage(msg, index); } const base = createBaseMessage(msg, index); const parts = msg.parts ? convertPartsArray(msg.parts) : buildPartsFromTopLevelFields(msg); return { ...base, parts }; } // V5 to V4 conversion function convertV5ToolUIPartToV4ToolInvocation( part: ToolUIPart, ): ToolInvocation { const state = part.state === 'input-streaming' ? 'partial-call' : part.state === 'input-available' ? 'call' : 'result'; const toolName = part.type.startsWith('tool-') ? part.type.slice(5) : part.type; const base = { toolCallId: part.toolCallId, toolName, args: part.input, state, }; if (state === 'result' && part.output !== undefined) { return { ...base, state: 'result' as const, result: part.output }; } return base as ToolInvocation; } export function convertV5MessageToV4(msg: MyUIMessage): LegacyUIMessage { const parts: V4Part[] = []; const base: LegacyUIMessage = { id: msg.id, role: msg.role, content: '', parts, }; let textContent = ''; let reasoning: string | undefined; const toolInvocations: ToolInvocation[] = []; for (const part of msg.parts) { if (part.type === 'text') { textContent = part.text; parts.push({ type: 'text', text: part.text }); } else if (part.type === 'reasoning') { reasoning = part.text; parts.push({ type: 'reasoning', reasoning: part.text, details: [{ type: 'text', text: part.text }], }); } else if (part.type.startsWith('tool-')) { const toolInvocation = convertV5ToolUIPartToV4ToolInvocation( part as ToolUIPart, ); parts.push({ type: 'tool-invocation', toolInvocation: toolInvocation }); toolInvocations.push(toolInvocation); } else if (part.type === 'source-url') { parts.push({ type: 'source', source: { id: part.sourceId, url: part.url, title: part.title, sourceType: 'url', }, }); } else if (part.type === 'file') { parts.push({ type: 'file', mimeType: part.mediaType, data: part.url, }); } else if (part.type === 'data-custom') { base.data = part.data; } } if (textContent) { base.content = textContent; } if (reasoning) { b