用途:整理 Vercel AI SDK 5 在构建 AI 聊天功能时的模式,重点是相对 v4 的破坏性变更。
主要变更:useChat 的导入位置从 ai 改为 @ai-sdk/react,并通过 transport 传参;原来直接传 api,现在使用 new DefaultChatTransport({ api: "/api/chat" });返回对象中 sendMessage 取代旧的 handleSubmit/input 等组合,发送时调用 sendMessage({ text: input })。
消息结构:v5 的 UIMessage 不再用 message.content 字符串,而是 message.parts 数组,part 类型包括 text、image、tool-call、tool-result;取文本需从 parts 中过滤 type 为 text 并拼接。
服务端:在路由处理函数中使用 streamText,配合模型(如 openai("gpt-4o"))与 messages、system,并用 result.toDataStreamResponse() 返回流。
LangChain 集成:使用 @ai-sdk/langchain 的 toUIMessageStream,将 LangChain 模型流转换为 UI 消息流,再调用 toDataStreamResponse;过程中需把 UI 消息的 parts 文本转成 HumanMessage/AIMessage。
工具调用:streamText 可传 tools,使用 ai 的 tool 与 zod 定义参数与 execute。
文本生成:useCompletion 从 @ai-sdk/react 引入,配合 DefaultCompletionTransport。错误处理:useChat 支持 onError 回调,并可展示 error.message 与重试。
限制:资料仅给出上述模式与代码片段,未提供版本兼容范围、安装命令、收费、性能或其他能力说明。