SuperAPI AI 工具集

ai-sdk

智能体与模型

查看项目

更新于 10-16 07:45

技能介绍

用途

该技能适用于使用 Vercel AI SDK v6 构建 AI 功能的场景,包括:构建流式聊天界面、使用 Zod schema 生成结构化 JSON 输出、带工具的多步智能体工作流、工具审批流程(人在回路),以及 Next.js App Router 集成。当使用 useChat、streamText 或 generateObject,或涉及“AI SDK”“streaming chat”等场景时,应使用本技能。

版本与依赖

目标为 AI SDK 6.x API。默认包为:ai@^6、@ai-sdk/react@^2、@ai-sdk/openai@^2(或 @ai-sdk/anthropic 等)、zod@^3。

需避免 v4/v5 的旧写法:StreamingTextResponse 应改为 result.toUIMessageStreamResponse();旧版 Message 形状应改为 UIMessage;输入受控的 useChat 应改为基于 transport 的模式。

核心概念

消息类型分为两类:UIMessage 面向用户与持久化,用于存入数据库、在 UI 中渲染;ModelMessage 与 LLM 兼容,仅在调用模型时转换使用。规则是:持久化 UIMessage[],仅在调用模型时转换为 ModelMessage[]。

流式相关函数用途:streamText 用于流式文本响应;generateText 用于非流式文本;streamObject 用于带部分更新的流式 JSON;generateObject 用于非流式 JSON;ToolLoopAgent 用于带工具的多步智能体。

使用方式

流式聊天黄金路径

服务端 API 路由(App Router)示例:在 app/api/chat/route.ts 中导入 openai、streamText、convertToModelMessages 与 UIMessage 类型,设置 maxDuration = 30,从请求体读取 messages: UIMessage[],调用 streamText 并传入 model 与 convertToModelMessages(messages),最后返回 result.toUIMessageStreamResponse(),其中可传入 originalMessages 与 getErrorMessage。

客户端 Hook 示例:使用 'use client',从 @ai-sdk/react 导入 useChat 与 UIMessage,从 ai 导入 DefaultChatTransport。组件接收 initialMessages,使用 useState 管理 input,调用 useChat 并传入 messages 与 transport: new DefaultChatTransport({ api: '/api/chat' }),从返回值取 messages、sendMessage、status、error。提交时调用 sendMessage({ role: 'user', content: [{ type: 'text', text: input }] })。渲染时遍历 messages,对每条消息遍历 m.parts,当 p.type === 'text' 时渲染 p.text;当 status === 'error' 时显示 error?.message。

结构化输出

使用 generateObject 与 streamObject,配合 zod 定义 schema。示例 schema 为 z.object({ recipe: z.object({ name: z.string(), ingredients: z.array(z.string()), steps: z.array(z.string()) }) })。一次性 JSON 使用 generateObject,传入 model、schema、prompt,从返回中取 object。流式 JSON 使用 streamObject,取 partialObjectStream,通过 for await 遍历 partial 以渐进渲染。

工具

服务端工具定义使用 tool,传入 description、inputSchema(zod)与 execute 异步函数。多步工具循环使用 streamText,传入 tools 对象与 stopWhen: stepCountIs(6) 限制最大迭代次数,并可用 prepareStep 在 messages 超过 10 条时截取最近 10 条。

v6:ToolLoopAgent

ToolLoopAgent 是面向自主多步工作流的一等智能体抽象。基础用法:new ToolLoopAgent({ model: 'anthropic/claude-sonnet-4.5', instructions, tools, stopWhen: stepCountIs(5) })。非流式调用 agent.generate({ prompt }),可读取 result.text 与 result.steps;流式调用 agent.stream({ prompt }),遍历 stream.textStream 输出。带 UI 流式时使用 createAgentUIStream({ agent, messages }),遍历返回的 chunk。

v6:工具审批(人在回路)

静态审批:在 tool 中设置 needsApproval: true,始终要求审批。动态审批:needsApproval 为异步函数,例如 ({ amount }) => amount > 1000,仅对大额交易要求审批。客户端审批 UI 中,当 invocation.state === 'approval-requested' 时显示审批按钮,调用 addToolApprovalResponse({ id: invocation.approval.id, approved: true/false });当 invocation.state === 'output-available' 时显示 invocation.output。

持久化

在 result.toUIMessageStreamResponse() 中传入 originalMessages、generateMessageId(如 createIdGenerator({ prefix: 'msg', size: 16 }))与 onFinish 回调,在回调中调用 saveChat({ chatId, messages: complete }) 持久化 UIMessage[]。

错误处理

服务端通过 getErrorMessage 将错误暴露给客户端,例如 e instanceof Error ? e.message : typeof e === 'string' ? e : JSON.stringify(e)。客户端从 useChat 取 status 与 error,当 status === 'error' 时渲染 error?.message。

反模式

应避免 StreamingTextResponse,改用 result.toUIMessageStreamResponse();避免持久化 ModelMessage,改为持久化 UIMessage[];避免无界工具循环,使用 stopWhen: stepCountIs(N);避免长会话仅用客户端状态,应加入持久化与可恢复流;避免 any 类型,使用 Zod schema 与类型化 UIMessage。

相关文档

agents.md 介绍 ToolLoopAgent 模式与工作流;tool-approval.md 介绍人在回路审批流程;persistence.md 介绍聊天持久化策略。