Vercel

next-forge

Get started
Back to Posts

Vercel AI SDK 6 实战:构建流式 AI 对话应用

从零开始使用 Vercel AI SDK 6 构建一个支持多模型、工具调用和流式输出的 AI 对话应用,涵盖 useChat、streamText 和 AI Gateway 的完整用法。

AI SDK 6 的核心变化

AI SDK 6 带来了重大 API 重构:useChat 改用 transport 模式,消息格式从 CoreMessage 升级为 UIMessage,streamText 的响应方法从 toDataStreamResponse 改为 toUIMessageStreamResponse。

接入 AI Gateway

不再需要为每个 AI 提供商配置单独的 API Key。通过 Vercel AI Gateway,只需在模型字符串中指定 provider/model(如 anthropic/claude-sonnet-4-5),即可透明地路由到对应提供商,并享受统一的可观测性。

工具调用最佳实践

AI SDK 6 的工具定义与 MCP 规范对齐,使用 inputSchema 替代 parameters,使用 output 替代 result。多步工具调用通过 stopWhen: stepCountIs(5) 控制循环次数,避免无限递归。

流式 UI 渲染

推荐使用 AI Elements(npx ai-elements)提供的 Message 和 MessageResponse 组件渲染 AI 输出,它们内置了 Markdown 解析、代码高亮和流式动画,无需手动处理 message.parts 迭代。

next-forge

This is the start of something new.

Pages

Post

Legal