migrate-ai-sdk-v6-to-v7
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAI SDK 6 to 7 Migration
AI SDK 6 迁移至 7.0 指南
Use from the AI SDK repo as the source of truth. This skill is the working checklist; read the guide for exact examples or when behavior is unclear.
content/docs/08-migration-guides/23-migration-guide-7-0.mdx以AI SDK仓库中的作为权威参考。本技能是实用检查清单;如需确切示例或对行为存疑,请阅读该指南。
content/docs/08-migration-guides/23-migration-guide-7-0.mdxMigration Workflow
迁移流程
- Ensure the user has a clean backup or committed baseline before editing.
- Inspect and lockfiles to identify installed
package.json,ai, provider, UI, MCP, and telemetry packages.@ai-sdk/* - Upgrade AI SDK packages to latest versions, and add only if the project uses OpenTelemetry spans.
@ai-sdk/otel - Update runtime and module assumptions: Node.js must be , and AI SDK packages are ESM-only. Replace
>=22imports with ESM imports and addrequire()or use"type": "module"where needed..mjs - Search for the v6 patterns below, migrate only the code that exists, then run typecheck and targeted tests.
Prefer behavior-preserving changes. When v7 changes semantics, decide whether the app wants the new all-steps behavior or the previous final-step-only behavior.
- 确保用户在编辑前有干净的备份或已提交的基线版本。
- 检查和锁文件,识别已安装的
package.json、ai、提供商、UI、MCP和遥测包。@ai-sdk/* - 将AI SDK包升级至最新版本,仅当项目使用OpenTelemetry追踪时才添加。
@ai-sdk/otel - 更新运行时和模块假设:Node.js版本必须为,且AI SDK包仅支持ESM。将
>=22导入替换为ESM导入,并在需要时添加require()或使用"type": "module"后缀。.mjs - 搜索下方的v6代码模式,仅迁移现有代码,然后运行类型检查和针对性测试。
优先选择保留原有行为的变更。当v7改变语义时,需决定应用是想要新的全步骤行为还是之前的仅最终步骤行为。
Core API Changes
核心API变更
- ->
experimental_customProvider.customProvider - ->
experimental_generateImage;generateImage->Experimental_GenerateImageResult.GenerateImageResult - ->
experimental_transcribe;transcribe->Experimental_TranscriptionResult.TranscriptionResult - ->
experimental_generateSpeech;generateSpeech->Experimental_SpeechResult.SpeechResult - option/result ->
experimental_outputoption/result.output - ->
CallSettings;LanguageModelCallOptions & Omit<RequestOptions, 'timeout'>->prepareCallSettings.prepareLanguageModelCallOptions - ->
stepCountIs.isStepCount
- 替换为
experimental_customProvider。customProvider - 替换为
experimental_generateImage;generateImage替换为Experimental_GenerateImageResult。GenerateImageResult - 替换为
experimental_transcribe;transcribe替换为Experimental_TranscriptionResult。TranscriptionResult - 替换为
experimental_generateSpeech;generateSpeech替换为Experimental_SpeechResult。SpeechResult - 选项/结果 替换为
experimental_output选项/结果。output - 替换为
CallSettings;LanguageModelCallOptions & Omit<RequestOptions, 'timeout'>替换为prepareCallSettings。prepareLanguageModelCallOptions - 替换为
stepCountIs。isStepCount
Prompts and Steps
提示词与步骤
- Rename top-level to
systemforinstructions,generateText,streamText,generateObject, andstreamObject.streamUI - Move messages from
{ role: 'system' }orpromptinto top-levelmessages. Only useinstructionsfor trusted persisted messages.allowSystemInMessages: true - Rename to
experimental_prepareStep.prepareStep - In , rename returned
prepareSteptosystem.instructions - In , use
experimental_repairToolCallinstead of{ instructions }.{ system } - Audit behavior: returned
prepareStepandinstructionsnow carry forward into later steps. If code depended on one-step-only overrides, rebuild frommessages,initialInstructions, andinitialMessagesexplicitly.responseMessages
- 对、
generateText、streamText、generateObject和streamObject,将顶层streamUI重命名为system。instructions - 将或
prompt中的messages消息移至顶层{ role: 'system' }中。仅对受信任的持久化消息使用instructions。allowSystemInMessages: true - 将重命名为
experimental_prepareStep。prepareStep - 在中,将返回的
prepareStep重命名为system。instructions - 在中,使用
experimental_repairToolCall替代{ instructions }。{ system } - 检查的行为:返回的
prepareStep和instructions现在会延续到后续步骤。如果代码依赖单步覆盖逻辑,请显式从messages、initialInstructions和initialMessages重新构建。responseMessages
Lifecycle Callbacks
生命周期回调
- ->
experimental_onStart.onStart - ->
experimental_onStepStart.onStepStart - ->
onFinish.onEnd - ->
onStepFinish.onStepEnd - For ,
embed, andembedMany,rerank->experimental_onFinish.onEnd - Callback event fields use instead of
instructions.system
- 替换为
experimental_onStart。onStart - 替换为
experimental_onStepStart。onStepStart - 替换为
onFinish。onEnd - 替换为
onStepFinish。onStepEnd - 对于、
embed和embedMany,rerank替换为experimental_onFinish。onEnd - 回调事件字段使用替代
instructions。system
Usage, Telemetry, and Include Options
使用量、遥测与包含选项
- ->
usage.cachedInputTokens.usage.inputTokenDetails.cacheReadTokens - ->
usage.reasoningTokens.usage.outputTokenDetails.reasoningTokens - OpenTelemetry moved out of ; install
aiand call@ai-sdk/otelat app startup.registerTelemetry(new OpenTelemetry(...)) - Telemetry is enabled by default once an integration is registered. Remove redundant ; use
isEnabled: trueto opt out per call.isEnabled: false - Move into the
experimental_telemetry.tracerconstructor.OpenTelemetry - ->
experimental_telemetry.telemetry - Telemetry integration callbacks: ->
onRerankFinish,onRerankEnd->onEmbedFinish. Update tracing-channel subscribers for the same event type names.onEmbedEnd - ->
experimental_include.include - ->
includeRawChunks.include.rawChunks - Request and response bodies are excluded by default. If code reads or
request.body, opt in withresponse.bodyand, forinclude.requestBody,generateText.include.responseBody
- 替换为
usage.cachedInputTokens。usage.inputTokenDetails.cacheReadTokens - 替换为
usage.reasoningTokens。usage.outputTokenDetails.reasoningTokens - OpenTelemetry已从包中移出;安装
ai并在应用启动时调用@ai-sdk/otel。registerTelemetry(new OpenTelemetry(...)) - 注册集成后,遥测默认启用。移除冗余的;如需按调用禁用,使用
isEnabled: true。isEnabled: false - 将移至
experimental_telemetry.tracer构造函数中。OpenTelemetry - 替换为
experimental_telemetry。telemetry - 遥测集成回调:替换为
onRerankFinish,onRerankEnd替换为onEmbedFinish。更新追踪通道订阅者以匹配新的事件类型名称。onEmbedEnd - 替换为
experimental_include。include - 替换为
includeRawChunks。include.rawChunks - 请求和响应体默认被排除。如果代码需要读取或
request.body,需通过response.body(对include.requestBody还需generateText)选择加入。include.responseBody
Streaming, Messages, and Tools
流式传输、消息与工具
- ->
StreamTextResult.fullStream.stream streamTextnow receives all stream parts, including lifecycle, boundary, finish, abort, and error parts. Guard byonChunkbefore assuming text/tool/raw content.chunk.type- is no longer accumulated across previous steps. Use
step.response.messagesfor the full response message history, or flattenresult.responseMessages.result.steps - Tool execution callbacks: ->
experimental_onToolCallStart,onToolExecutionStart->experimental_onToolCallFinish.onToolExecutionEnd - Tool callback ->
experimental_context.context - Split shared runtime data from tool-specific data: use top-level for orchestration state, declare per-tool
runtimeContext, and pass per-tool values throughcontextSchema.toolsContext - Move from
needsApproval/tool()into per-call or agentdynamicTool().toolApproval - ->
experimental_activeTools.activeTools - ->
ToolCallOptions.ToolExecutionOptions - ->
isToolOrDynamicToolUIPart.isToolUIPart
- 替换为
StreamTextResult.fullStream。stream - 的
streamText现在会接收所有流部分,包括生命周期、边界、完成、中止和错误部分。在假设内容为文本/工具/原始类型前,需先判断onChunk。chunk.type - 不再累积之前步骤的内容。如需完整的响应消息历史,使用
step.response.messages,或展开result.responseMessages。result.steps - 工具执行回调:替换为
experimental_onToolCallStart,onToolExecutionStart替换为experimental_onToolCallFinish。onToolExecutionEnd - 工具回调的替换为
experimental_context。context - 将共享运行时数据与工具特定数据分离:使用顶层存储编排状态,声明每个工具的
runtimeContext,并通过contextSchema传递工具专属值。toolsContext - 将从
needsApproval/tool()移至单次调用或agent的dynamicTool()中。toolApproval - 替换为
experimental_activeTools。activeTools - 替换为
ToolCallOptions。ToolExecutionOptions - 替换为
isToolOrDynamicToolUIPart。isToolUIPart
Content Parts and Reasoning
内容部分与推理
- Tool result is removed; use
{ type: 'media' }.{ type: 'file-data' } - Migrate
toModelOutput,image-*,file-*, andfile-idvariants to canonicalimage-file-id.{ type: 'file', mediaType, data: { type: 'data' | 'url' | 'reference', ... } } - User message is deprecated; use
{ type: 'image', image, mediaType? }.{ type: 'file', mediaType: 'image' | 'image/*', data } - Add support for the new content type in exhaustive switches, renderers, serializers, and validators.
reasoning-file - When adopting top-level , remove overlapping provider-specific reasoning settings from
reasoningunless provider-specific settings intentionally take precedence.providerOptions
- 移除工具结果中的;改用
{ type: 'media' }。{ type: 'file-data' } - 将的
toModelOutput、image-*、file-*和file-id变体迁移为标准格式image-file-id。{ type: 'file', mediaType, data: { type: 'data' | 'url' | 'reference', ... } } - 用户消息中的已弃用;改用
{ type: 'image', image, mediaType? }。{ type: 'file', mediaType: 'image' | 'image/*', data } - 在穷举开关、渲染器、序列化器和验证器中添加对新内容类型的支持。
reasoning-file - 采用顶层时,移除
reasoning中重复的提供商特定推理设置,除非有意让提供商特定设置优先。providerOptions
Multi-Step Result Shape
多步骤结果结构
- now includes all steps;
result.usageis deprecated. Useresult.totalUsagefor final-step-only usage.result.finalStep.usage - Top-level ,
content,toolCalls,staticToolCalls,dynamicToolCalls,toolResults,staticToolResults,dynamicToolResults,files, andsourcesnow include all steps. Usewarningsfor previous final-step-only behavior.finalStep - Top-level ,
reasoning,reasoningText,request, andresponseare deprecated for final-step data. UseproviderMetadata; forresult.finalStep.*, awaitstreamText.result.finalStep - Apply the same result-shape rules to events.
onEnd
- 现在包含所有步骤;
result.usage已弃用。如需仅最终步骤的使用量,使用result.totalUsage。result.finalStep.usage - 顶层的、
content、toolCalls、staticToolCalls、dynamicToolCalls、toolResults、staticToolResults、dynamicToolResults、files和sources现在包含所有步骤。如需之前仅最终步骤的行为,使用warnings。finalStep - 顶层的、
reasoning、reasoningText、request和response已弃用,用于获取最终步骤数据请使用providerMetadata;对result.finalStep.*,需等待streamText。result.finalStep - 将相同的结果结构规则应用于事件。
onEnd
Stream Response Helpers
流响应助手
The result helper methods are deprecated. Replace result methods with top-level stateless helpers:
streamText- ->
result.toUIMessageStream(...).toUIMessageStream({ stream: result.stream, ... }) - ->
result.toUIMessageStreamResponse(...)plustoUIMessageStream(...).createUIMessageStreamResponse({ stream }) - ->
result.pipeUIMessageStreamToResponse(response, ...)plustoUIMessageStream(...).pipeUIMessageStreamToResponse({ response, stream }) - ->
result.toTextStreamResponse()plustoTextStream({ stream: result.stream }).createTextStreamResponse({ stream }) - ->
result.pipeTextStreamToResponse(response)plustoTextStream({ stream: result.stream }).pipeTextStreamToResponse({ response, stream })
streamText- 替换为
result.toUIMessageStream(...)。toUIMessageStream({ stream: result.stream, ... }) - 替换为
result.toUIMessageStreamResponse(...)加上toUIMessageStream(...)。createUIMessageStreamResponse({ stream }) - 替换为
result.pipeUIMessageStreamToResponse(response, ...)加上toUIMessageStream(...)。pipeUIMessageStreamToResponse({ response, stream }) - 替换为
result.toTextStreamResponse()加上toTextStream({ stream: result.stream })。createTextStreamResponse({ stream }) - 替换为
result.pipeTextStreamToResponse(response)加上toTextStream({ stream: result.stream })。pipeTextStreamToResponse({ response, stream })
Package-Specific Checks
包特定检查
- MCP: now defaults to
MCPTransportConfig.redirect. Only set'error'for trusted MCP servers that rely on redirects.redirect: 'follow' - Vue:
@ai-sdk/vueclass is deprecated. PreferChat, including getter/ref init for reactive chat inputs.useChat - Anthropic and :
@ai-sdk/google-vertex/anthropicwas removed. UseproviderMetadata.anthropic.cacheCreationInputTokens; raw Anthropic usage remains atusage.inputTokenDetails.cacheWriteTokens.finalStep.providerMetadata?.anthropic?.usage - Google: rename types, classes, and functions to
GoogleGenerativeAI*, e.g.Google*->createGoogleGenerativeAI. ThecreateGoogleentry point is unchanged.google
- MCP:现在默认值为
MCPTransportConfig.redirect。仅当受信任的MCP服务器依赖重定向时,才设置'error'。redirect: 'follow' - Vue:的
@ai-sdk/vue类已弃用。优先使用Chat,包括为响应式聊天输入初始化getter/ref。useChat - Anthropic和:移除了
@ai-sdk/google-vertex/anthropic。使用providerMetadata.anthropic.cacheCreationInputTokens;原始Anthropic使用量仍可通过usage.inputTokenDetails.cacheWriteTokens获取。finalStep.providerMetadata?.anthropic?.usage - Google:将类型、类和函数重命名为
GoogleGenerativeAI*,例如Google*替换为createGoogleGenerativeAI。createGoogle入口点保持不变。google
Validation
验证
Run the project typecheck after edits, then the smallest relevant test suite. Also smoke-test streaming, chat UI, tool execution, telemetry, and multi-step flows if the migration touched them. If type errors remain, search the migration guide for the exact removed or renamed symbol before inventing a workaround.
编辑后运行项目类型检查,然后运行最小相关测试套件。如果迁移涉及流式传输、聊天UI、工具执行、遥测和多步骤流程,还需进行冒烟测试。如果仍存在类型错误,请先在迁移指南中搜索已移除或重命名的符号,再尝试寻找解决方法。