后端与接口
AI SDK 6 Beta 中构建 Agent…
适用于 TypeScript 项目采用 AI SDK 6 Beta,需要实现 Agent、工具审批、结构化输出、重排序,并通过 Groq 或 Vercel AI Gateway 接入模型。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 38/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 60/100 ×0.15
适用场景
AI SDK 6 Beta 中构建 Ag特定
解决思路
- 查阅 AI SDK 6 Beta 文档:https://v6.ai-sdk.dev/docs/announcing-ai-sdk-6-beta
- 查阅 Groq Provider 文档:https://v6.ai-sdk.dev/providers/ai-sdk-providers/groq
- 查阅 Vercel AI Gateway 文档:https://v6.ai-sdk.dev/providers/ai-sdk-providers/ai-gateway
- 查阅 AI SDK GitHub:https://github.com/vercel/ai
- 查阅 Groq Console Models:https://console.groq.com/docs/models
- 安装 AI SDK 6 Beta 依赖:运行 `pnpm add ai@beta @ai-sdk/openai@beta @ai-sdk/react@beta @ai-sdk/groq@beta`。
- Beta 期间固定版本,避免补丁版本引入破坏性变更。
- 新增 Agent 抽象:用 `ToolLoopAgent` 构建 agent,统一控制执行流、工具循环和状态管理;从 `ai` 导入 `ToolLoopAgent`、`tool`,从 `zod` 导入 `z`。
- 定义工具:使用 `tool({ description, inputSchema: z.object(...), execute: async (...) => ... })`。
- 创建 `ToolLoopAgent`:传入 `model: 'groq/llama-3.3-70b-versatile'` 或任意模型、`instructions`、`tools`。
- 调用 agent:`const result = await agent.generate({ prompt: '...' });`,读取 `result.output`。
- 工具执行审批:在敏感工具上设置 `needsApproval: true`。
- 审批客户端 UI:检查 `invocation.state === 'approval-requested'`,展示金额和接收方等输入信息。
- 审批响应:按钮调用 `addToolApprovalResponse({ id: invocation.approval.id, approved: true/false })` 来批准或拒绝。
- 结构化输出 + 工具调用稳定:在 `ToolLoopAgent` 中设置 `output: Output.object({ schema: z.object(...) })`。
- 生成后读取解构出的 `output`,例如 `const { output } = await agent.generate(...)`。
- 重排序支持:从 `ai` 导入 `rerank`,从 `@ai-sdk/cohere` 导入 `cohere`。
- 调用 `rerank({ model: cohere.reranking('rerank-v3.5'), documents, query, topN })`,读取 `ranking`,其中包含 `originalIndex`、`score`、`document`。
- 从 AI SDK 5 迁移:预期破坏性变更很少,大多数 AI SDK 5 代码只需少量修改。
- 迁移差异:Agent 抽象替代临时模式,考虑迁移到 `ToolLoopAgent`。
- 迁移差异:结构化输出现在可用于 `generateText` / `streamText`,但需要 `stopWhen`。
- 迁移差异:Beta 期间 `@ai-sdk/*` 包可能有小幅 API 调整。
- Groq Provider 安装:运行 `pnpm add @ai-sdk/groq`。
- Groq 环境变量:设置 `GROQ_API_KEY=your_groq_api_key`。
- 选择 Groq 开放权重模型:`llama-3.3-70b-versatile`(平衡)、`llama-3.1-8b-instant`(快速)、`mixtral-8x7b-32768`、`gemma2-9b-it`、`qwen/qwen3-32b`;完整列表见 Groq console。
- Groq 基础 Llama 示例:从 `@ai-sdk/groq` 导入 `groq`,用 `generateText({ model: groq('llama-3.3-70b-versatile'), prompt })`,读取 `text`。
- Groq 结构化输出:用 `generateObject`,传入 `model: groq('llama-3.3-70b-versatile')`、Zod `schema`、`prompt`,并设置 `providerOptions.groq.structuredOutputs: true`。
- Groq 工具使用:定义 `weatherTool`,用 `generateText({ model: groq('llama-3.3-70b-versatile'), prompt, tools: { weather: weatherTool } })`,读取 `text`。
- Groq 推理模型:使用 `qwen/qwen3-32b` 或 `deepseek-r1-distill-llama-70b`。
- Groq 推理配置:设置 `providerOptions.groq.reasoningFormat` 为 `'parsed'`、`'hidden'` 或 `'raw'`,并设置 `reasoningEffort` 为 `low`、`medium`、`high`(默认 `default`)。
- Groq 图像输入:使用多模态模型 `meta-llama/llama-4-scout-17b-16e-instruct`,在 `messages` 中传 `content` 数组,包含 `{ type: 'text', text: '...' }` 和 `{ type: 'image', image: 'https://example.com/image.jpg' }`。
- Vercel AI Gateway 用途:通过单一 API 访问 20+ 提供商的模型(OpenAI、Anthropic、Google、Groq、xAI、Mistral 等);需要 Vercel 账号和信用卡。
- Gateway 环境变量:设置 `AI_GATEWAY_API_KEY=your_gateway_api_key`,从 Vercel Dashboard > AI Gateway 获取 key。
- Gateway 计费提醒:使用 Gateway 需要信用卡,按模型调用计费。
- Gateway API Key 认证:用 `createGateway({ apiKey: process.env.AI_GATEWAY_API_KEY })`。
- Gateway OIDC 认证:部署到 Vercel 时生产/预览自动处理 OIDC,无需 API key。
- Gateway 本地开发 OIDC:安装并认证 Vercel CLI:`vercel login`;拉取 OIDC token:`vercel env pull`;用 `vercel dev` 启动开发服务器以自动刷新 token。
- OIDC token 12 小时过期;用 `vercel dev` 自动刷新,或手动重新运行 `vercel env pull`。
- Gateway 基础用法:直接使用模型字符串 `creator/model-name`,例如 `model: 'openai/gpt-5'`。
- Gateway 实例:用 `createGateway({ apiKey })`,然后 `model: gateway('anthropic/claude-sonnet-4')`。
- Gateway 动态模型发现:调用 `gateway.getAvailableModels()`,遍历 `availableModels.models` 打印 `model.id`、`model.name`,如存在 `model.pricing` 打印输入/输出 token 价格。
- 使用发现的第一个模型:`model: availableModels.models[0].id`。
- Gateway 检查额度:调用 `gateway.getCredits()`,读取 `credits.balance` 和 `credits.total_used`。
- Gateway 流式输出:用 `streamText({ model: 'openai/gpt-5', prompt })`,遍历 `textStream` 写入输出。
- Gateway 工具使用:定义 `weatherTool`,用 `generateText({ model: 'xai/grok-4', prompt, tools: { getWeather: weatherTool } })`。
- Gateway BYOK:在 `providerOptions.gateway.byok` 中传入自有凭证,例如 `anthropic: [{ apiKey: 'sk-ant-...' }]`,并满足 `GatewayProviderOptions`。
- BYOK 配置:在 Vercel 团队的 AI Gateway 设置中配置 BYOK 凭证;配置后无需改代码。
- Gateway 提供商执行工具:某些提供商提供服务器端执行工具(如 OpenAI web search);通过 Gateway 使用时导入 provider,例如 `openai.tools.webSearch({})`,并设置 `stopWhen: stepCountIs(10)`。
- 注意:需要账号特定配置的工具(如 Claude Agent Skills)可能需要通过 BYOK 直接访问 provider。
- Gateway 核心路由选项:`order`(按顺序尝试提供商/回退优先级)、`only`(限制特定提供商)、`models`(主模型失败时回退到替代模型)、`user`(按最终用户跟踪用量)、`tags`(为分析分类请求)、`zeroDataRetention`(仅使用零数据保留提供商)、`byok`(请求级 BYOK 凭证)。
- Gateway 提供商与模型回退示例:设置 `providerOptions.gateway.order: ['vertex', 'anthropic']`、`only: ['vertex', 'anthropic']`、`models: ['openai/gpt-5-nano', 'gemini-2.0-flash']`、`user`、`tags`;回退顺序会先尝试 vertex+主模型,再 anthropic+主模型,再 vertex+备用模型,再 anthropic+备用模型等。
- Gateway 用量跟踪示例:设置 `providerOptions.gateway.user: 'user-abc-123'` 和 `tags: ['document-summary', 'premium-feature']`,在 Vercel Dashboard 按用户和功能查看分析。
- Gateway 零数据保留:对敏感数据设置 `providerOptions.gateway.zeroDataRetention: true`,Gateway 只路由到不保留数据的提供商;省略或 false 不强制执行。
- Agent 调用选项:用 `callOptionsSchema: z.object({ userId, accountType })` 配置运行时选项。
- Agent 动态配置:用 `prepareCall: ({ options, ...settings }) => ({ ...settings, instructions: settings.instructions + ... })` 根据 options 修改调用设置。
- 调用带 options 的 agent:`supportAgent.generate({ prompt, options: { userId, accountType } })`。
- React UI 集成服务端:用 `createAgentUIStreamResponse({ agent: weatherAgent, messages })` 返回 UI 流响应。
- React UI 集成客户端:用 `InferAgentUIMessage<typeof weatherAgent>` 推导消息类型,并用 `useChat<AgentMessage>()` 获取 `messages` 和 `sendMessage`。
- Groq 最佳实践:平衡性能与成本选 `llama-3.3-70b-versatile`。
- Groq 最佳实践:低延迟、轻量任务选 `llama-3.1-8b-instant`。
- Groq 最佳实践:启用 `parallelToolCalls: true`(默认)以加快多工具执行。
- Groq 最佳实践:可忍受偶发失败时用 `serviceTier: 'flex'` 获得 10x 速率限制。
- Vercel AI Gateway 最佳实践:始终添加信用卡;gateway 按 token 付费。
- Vercel AI Gateway 最佳实践:用 `only` / `order` 控制路由和成本。
- Vercel AI Gateway 最佳实践:用 `user` 和 `tags` 跟踪支出和调试。
- Vercel AI Gateway 最佳实践:敏感数据启用 `zeroDataRetention`。
- Vercel AI Gateway 最佳实践:定期检查 `gateway.getCredits()` 监控用量。
- Agent 最佳实践:以 `ToolLoopAgent` 为起点,必要时再扩展。
- Agent 最佳实践:组合结构化输出与工具调用,获得丰富响应。
- Agent 最佳实践:对支付/删除等操作使用工具审批。
- Agent 最佳实践:设置 `stopWhen` 控制循环迭代(默认 `stepCountIs(20)`)。
- RAG Agent 模式:创建 `ToolLoopAgent`,工具 `searchDocs` 根据 query 调用向量数据库(Upstash、Pinecone 等)并返回 docs,`instructions` 指示通过搜索文档回答问题。
- 多提供商回退模式:用 `generateText`,在 `providerOptions.gateway.models` 中设置 `['openai/gpt-5', 'gemini-2.0-flash']` 作为回退模型。
- 成本优化选择模式:根据查询是否敏感选择模型,例如包含 `payment` 时用 `anthropic/claude-sonnet-4`,否则用 `openai/gpt-5-nano`。
- 时间线:AI SDK 6 Beta 现已可用(固定版本)。
- 时间线:稳定版预计 2025 年底发布。
适用边界 · 注意事项
- 不适用于不使用 TypeScript / AI SDK 的项目,或仍锁定 AI SDK 5 且无迁移计划的生产系统。
- 不适用于无法接受 Beta 不稳定、需要稳定版生产的场景。
- 不适用于无法创建 Vercel 账号/信用卡或不愿使用 Groq、Vercel AI Gateway 的项目。