页面简介
Complete migration guide from AI SDK v4 to v5 with real-world experience
正文摘录
BUIDLHow We Migrated atypica.AI to AI SDK v5 Without Breaking 10M+ Chat Historiesweb3nomad.ethOct 07, 20252Shareatypica.AI is a multi-agent research platform where AI agents collaborate to conduct user research. Users ask business questions, and the system orchestrates multiple specialized agents—Study Agent plans research, Scout Agent discovers target users from social media, Interview Agent conducts automated interviews with AI personas, and Report Agent generates comprehensive insights. The entire process involves 30+ AI tools and generates extensive chat histories stored in PostgreSQL.When Vercel released AI SDK v5 with breaking changes to message formats and tool APIs, we faced a challenge: migrate 200 files and 30+ tools while keeping 10 million+ existing chat conversations accessible. This article documents our 3-day migration journey.Final stats: 200 files changed, 4,206 insertions, 3,094 deletions, 27 commits.The Core Breaking Change: Message → UIMessageThe most fundamental change in v5 is how messages are structured.v4: Message with content + parts// v4 Message { id: “msg1”, role: “assistant”, content: “The weather is sunny”, // String representation parts: [ // Structured data (optional) { type: “text”, text: “The weather is “ }, { type: “tool-invocation”, toolInvocation: { ... } }, { type: “text”, text: “sunny” } ] }In v4, you could use either content (simple string) or parts (structured array). Most of our code used content because it was simpler.v5: UIMessage with parts only// v5 UIMessage { id: “msg1”, role: “assistant”, parts: [ // Only source of truth { type: “text”, text: “The weather is “ }, { type: “tool-getWeather”, toolCallId: “...”, state: “output-available”, output: {...} }, { type: “text”, text: “sunny” } ], content: “The weather is sunny” // Auto-generated, read-only }In v5, parts is the only source of truth. The content field is automatically derived from parts and is read-only.Migration impact: Every place that accessed message.content needed to be refactored to iterate through message.parts.Day 1: Understanding the ScopeRunning the Codemodnpm install ai@^5.0.59 zod@^4.0.0 npx @ai-sdk/codemod@latest upgradeThe codemod handled mechanical replacements:Type name: Message → UIMessageTool API: parameters → inputSchemaAdded outputSchema placeholdersBut it left many FIXME comments because it couldn’t understand semantic changes.The First Major Problem: Content AccessWe had code like this everywhere:// v4 pattern - accessing content directly const lastMessage = messages[messages.length - 1]; if (lastMessage.content.includes(”weather”)) { // ... } // For title generation const title = message.content.substring(0, 50); // For logging logger.info({ userMessage: message.content });v5 migration: We created a utility to extract text from parts:// messageUtils.ts export function getTextFromParts(parts: UIMessage[”parts”]): string { return parts .filter((part) => part.type === “text”) .map((part) => part.text) .join(”“); } // Usage const text = getTextFromParts(message.parts); if (text.includes(”weather”)) { // ... }This pattern appeared in:Message persistence (16 files)UI components (25 files)API routes (15 files)Logging and analytics (8 files)Tool Invocation Structure ChangedThis was the second major breaking change.v4 tool part structure:{ type: “tool-invocation”, toolInvocation: { state: “result”, toolCallId: “call_123”, toolName: “searchPersonas”, args: { query: “coffee lovers” }, result: { personas: [...] } } }v5 tool part structure:{ type: “tool-searchPersonas”, // Typed as tool-${toolName} toolCallId: “call_123”, state: “output-available”, // States renamed input: { query: “coffee lovers” }, // args → input output: { personas: [...] } // result → output }Key changes:Flattened structure (no nested toolInvocation object)Type is specific: “tool-${toolName}” not generic “tool-invocation”State names: “call” → “input-available”, “result” → “output-available”Field names: args → input, result → outputAdded error state: “output-error” with errorTextReasoning Format Changed// v4 { type: “reasoning”, reasoning: “Let me think...” } // v5 { type: “reasoning”, text: “Let me think...” }Field name changed from reasoning to text.Day 2: Backward Compatibility for 10M+ MessagesThe Database ChallengeOur PostgreSQL database stores messages in v4 format:SELECT parts FROM chat_messages WHERE id = ‘msg_old’; -- Returns v4 format with tool-invocation and reasoning fieldsUsers expect to:Open old chat conversationsContinue conversations seamlesslySee tool results from old interactionsWe couldn’t migrate the database because:10M+ messages across 50+ tablesDowntime was unacceptableRisk of data corruption too highSolution: Conversion LayerCreated src/ai/v4.ts:export type V4ToolInvocation = | { state: “call”; toolCallId: string; toolName: string; args: any } | { state: “result”; toolCallId: string; toolName: string; args: any; result: any }; export type V4MessagePart = | { type: “text”; text: string } | { type: “reasoning”; reasoning: string } // v4 format | { type: “tool-invocation”; toolInvocation: V4ToolInvocation }; export type V5MessagePart = UIMessage[”parts”][number]; export function convertToV5MessagePart(part: V4MessagePart | V5MessagePart): V5MessagePart { // Text parts are identical in v4 and v5 if (part.type === “text”) { return part; } // Reasoning: reasoning field → text field if (part.type === “reasoning”) { if (”reasoning” in part) { return { type: “reasoning”, text: part.reasoning }; } return part; // Already v5 } // Tool invocation: nested → flat, args/result → input/output if (part.type === “tool-invocation” && “toolInvocation” in part) { const inv = part.toolInvocation; return { type: `tool-${inv.toolName}`, toolCallId: inv.toolCallId, state: inv.state === “result” ? “output-available” : “input-available”, input: inv.args, output: inv.state === “result” ? inv.result : undefined, } as V5MessagePart; } // Already v5 format return part as V5MessagePart; }Apply Conversion on Read// messageUtils.ts export async function convertDBMessagesToAIMessages(userChatId: string): Promise<UIMessage[]> { const dbMessages = await prisma.chatMessage.findMany({ where: { userChatId }, orderBy: { createdAt: “asc” }, }); return dbMessages.map((msg) => ({ id: msg.messageId, role: msg.role as “user” | “assistant”, parts: (msg.parts as V4MessagePart[]).map(convertToV5MessagePart), })); }Result: Old messages load transparently. New messages save in v5 format. No database migration needed.Type System ReorganizationWe have 5 independent chat systems with different tools:Study: 20+ tools (reasoning, search, interviews, reports, social media)Interview: 2 tools (endInterview, requestInteractionForm)Persona: 1 tool (endInterview)NewStudy: 1 tool (endInterview)Agents: 3 tools (thanks, hello, scout)Initial approach: One global UIToolConfigs type.Problem: Type pollution. Study components got autocomplete for Interview tools. Runtime errors from tool type mismatches.Solution: Domain-specific tool types.// src/ai/tools/types.ts - Study system export type StudyUITools = { reasoningThinking: { input: z.infer<typeof reasoningThinkingInputSchema>; output: z.infer<typeof reasoningThinkingOutputSchema>; }; searchPersonas: { input: z.infer<typeof searchPersonasInputSchema>; output: z.infer<typeof searchPersonasOutputSchema>; }; // ... 20+ other tools }; export type TStudyMessageWithTool = UIMessage<unknown, UIDataTypes, StudyUITools>; // src/app/(interviewProject)/tools/types.ts - Interview system export type TInterviewUITools = { endInterview: { input: z.infer<typeof endInterviewInputSchema>; output: z.infer<typeof endInterviewOutputSchema>; }; requestInteractionForm: { input: z.infer<typeof requestInteractionFormInputSchema>; output: z.infer<typeof requestInteractionFormOutputSchema>; }; }; export type TInterviewMessageWithTool = UIMessage<unknown, UIDataTypes, TInterviewUITools>;Each domain gets its own directory structure:src/app/(myDomain)/ ├── tools/ │ ├── types.ts # Tool type definitions │ └── ui.tsx # Tool UI rendering └── types.ts # Message type for this domainBenefit: Full type safety within each domain. No cross-contamination.Day 3: UI Components and Model MessagesComponent Migration PatternBefore v5, components accessed content directly:// v4 component export function ChatMessage({ message }: { message: Message }) { return <div>{message.content}</div>; }After v5, components iterate over parts:// v5 component export function ChatMessage({ message }: { message: UIMessage }) { return ( <div> {message.parts.map((part, i) => { if (part.type === “text”) { return <Markdown key={i}>{part.text}</Markdown>; } else if (part.type === “reasoning”) { return <ReasoningBlock key={i}>{part.text}</ReasoningBlock>; } else if (part.type.startsWith(”tool-”)) { return <ToolDisplay key={i} toolPart={part} />; } })} </div> ); }Tool detection pattern:// v4 if (part.type === “tool-invocation”) { const toolName = part.toolInvocation.toolName; const result = part.toolInvocation.result; } // v5 if (part.type.startsWith(”tool-”) && “toolCallId” in part) { const toolName = part.type.replace(”tool-”, “”); const output = part.state === “output-available” ? part.output : undefined; }We migrated 25+ UI components with this pattern.The UIMessage vs ModelMessage DistinctionThere’s one more important detail: messages to the model have a different format.UIMessage - From model, for UI:{ role: “user”, parts: [{ type: “text”, text: “Hello” }] }UserModelMessage - To model:{ role: “user”, content: [{ type: “text”, text: “Hello” }] // Note: content, not parts }This only matters when constructing messages for streamText or generateObject:import { UserModelMessage } from “ai”; const result = await streamText({ model: llm(”gpt-4”), messages: [ { role: “user”, content: [{ type: “text”, text: prompt }] // content for model } ] as UserModelMessage[], tools: { ... } });We had to fix this in 30+ tool definitions and artifact generators.useChat Hook Changes// v4 const { append, reload