关于 ai-sdk-6-skills
ai-sdk-6-skills 汇总 Vercel AI SDK 6 Beta 的开发指导,面向构建 Agent 和生成式 AI 应用的开发者。内容涵盖工具循环、结构化输出、Groq 与 AI Gateway,并介绍提供商路由、回退和 React UI 集成。
主要功能
- 01ToolLoopAgent 与执行控制
- 02工具调用审批和结构化输出
- 03Groq 提供商接入示例
- 04AI Gateway 多提供商路由
- 05React UI 集成模式
适用场景
- 01构建带工具调用的 Agent
- 02要求敏感工具执行前确认
- 03在模型提供商之间配置回退
- 04用 Groq 生成文本或结构化数据
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ gocallum/ nextjs16-agent-skills --skill ai-sdk-6-skills安装后在 Claude Code 中输入/ai-sdk-6-skills确认已加载。
详细介绍
链接
- 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 模型:https://console.groq.com/docs/models
安装
pnpm add ai@beta @ai-sdk/openai@beta @ai-sdk/react@beta @ai-sdk/groq@beta
注意:Beta 期间请锁定版本,因为补丁版本中可能会出现不兼容变更。
AI SDK 6 有哪些新功能?
1. Agent 抽象(新增)
用于构建 Agent 的统一接口,可全面控制执行流程、工具循环和状态管理。
import { ToolLoopAgent } from 'ai';
import { tool } from 'ai';
import { z } from 'zod';
const weatherTool = tool({
description: 'Get weather for a location',
inputSchema: z.object({ city: z.string() }),
execute: async ({ city }) => ({ temperature: 72, condition: 'sunny' }),
});
const agent = new ToolLoopAgent({
model: 'groq/llama-3.3-70b-versatile', // or any model
instructions: 'You are a helpful weather assistant.',
tools: { weather: weatherTool },
});
// Use the agent
const result = await agent.generate({
prompt: 'What is the weather in San Francisco?',
});
console.log(result.output);
2. 工具执行审批(新增)
在执行敏感工具前请求用户确认。
import { tool } from 'ai';
import { z } from 'zod';
const paymentTool = tool({
description: 'Process a payment',
inputSchema: z.object({
amount: z.number(),
recipient: z.string(),
}),
needsApproval: true, // Require approval
execute: async ({ amount, recipient }) => {
return { success: true, id: 'txn-123' };
},
});
客户端审批 UI:
export function PaymentToolView({ invocation, addToolApprovalResponse }) {
if (invocation.state === 'approval-requested') {
return (
<div>
<p>Process payment of ${invocation.input.amount} to {invocation.input.recipient}?</p>
<button
onClick={() =>
addToolApprovalResponse({
id: invocation.approval.id,
approved: true,
})
}
>
Approve
</button>
<button
onClick={() =>
addToolApprovalResponse({
id: invocation.approval.id,
approved: false,
})
}
>
Deny
</button>
</div>
);
}
return null;
}
3. 结构化输出 + 工具调用(稳定)
将工具调用与结构化输出生成相结合:
import { ToolLoopAgent, Output } from 'ai';
import { z } from 'zod';
const agent = new ToolLoopAgent({
model: 'groq/llama-3.3-70b-versatile',
tools: { /* ... */ },
output: Output.object({
schema: z.object({
summary: z.string(),
temperature: z.number(),
recommendation: z.string(),
}),
}),
});
const { output } = await agent.generate({
prompt: 'What is the weather in San Francisco and what should I wear?',
});
console.log(output);
// { summary: '...', temperature: 72, recommendation: '...' }
4. 重排序支持(新增)
通过重新排列文档来提升搜索相关性:
import { rerank } from 'ai';
import { cohere } from '@ai-sdk/cohere';
const { ranking } = await rerank({
model: cohere.reranking('rerank-v3.5'),
documents: [
'sunny day at the beach',
'rainy afternoon in the city',
'snowy night in the mountains',
],
query: 'talk about rain',
topN: 2,
});
console.log(ranking);
// [
// { originalIndex: 1, score: 0.9, document: 'rainy afternoon...' },
// { originalIndex: 0, score: 0.3, document: 'sunny day...' }
// ]
从 AI SDK 5 迁移
预计只会有极少的不兼容变更。大多数 AI SDK 5 代码只需稍作修改即可使用。
主要差异:
- Agent 抽象取代临时实现模式;请考虑迁移到
ToolLoopAgent。 - 结构化输出现在可与
generateText/streamText搭配使用(需要stopWhen)。 @ai-sdk/*包在 Beta 期间可能会有小幅 API 调整。
Groq Provider(开放权重模型)
设置
pnpm add @ai-sdk/groq
环境:
GROQ_API_KEY=your_groq_api_key
可用的开放权重模型
适用于 AI SDK 6 的常用 Groq 模型:
llama-3.3-70b-versatile(Llama 3.3,70B,性能均衡)llama-3.1-8b-instant(Llama 3.1,8B,速度快)mixtral-8x7b-32768(专家混合模型)gemma2-9b-it(Google Gemma 2)qwen/qwen3-32b(Qwen 3)
完整列表请参阅 Groq 控制台。
Llama 基本示例
import { groq } from '@ai-sdk/groq';
import { generateText } from 'ai';
const { text } = await generateText({
model: groq('llama-3.3-70b-versatile'),
prompt: 'Write a TypeScript function to compute Fibonacci.',
});
console.log(text);
使用 Llama 生成结构化输出(Groq)
import { groq } from '@ai-sdk/groq';
import { generateObject } from 'ai';
import { z } from 'zod';
const result = await generateObject({
model: groq('llama-3.3-70b-versatile'),
schema: z.object({
recipe: z.object({
name: z.string(),
ingredients: z.array(z.string()),
instructions: z.array(z.string()),
}),
}),
prompt: 'Generate a simple pasta recipe.',
providerOptions: {
groq: {
structuredOutputs: true, // Enable for supported models
},
},
});
console.log(JSON.stringify(result.object, null, 2));
使用 Llama 调用工具(Groq)
import { groq } from '@ai-sdk/groq';
import { generateText, tool } from 'ai';
import { z } from 'zod';
const weatherTool = tool({
description: 'Get weather for a city',
inputSchema: z.object({ city: z.string() }),
execute: async ({ city }) => ({ temp: 72, condition: 'sunny' }),
});
const { text } = await generateText({
model: groq('llama-3.3-70b-versatile'),
prompt: 'What is the weather in NYC and LA?',
tools: { weather: weatherTool },
});
console.log(text);
推理模型(Groq)
Groq 提供 qwen/qwen3-32b 和 deepseek-r1-distill-llama-70b 等推理模型:
import { groq } from '@ai-sdk/groq';
import { generateText } from 'ai';
const { text } = await generateText({
model: groq('qwen/qwen3-32b'),
providerOptions: {
groq: {
reasoningFormat: 'parsed', // 'parsed', 'hidden', or 'raw'
reasoningEffort: 'default', // low, medium, high
},
},
prompt: 'How many "r"s are in the word "strawberry"?',
});
console.log(text);
使用 Llama 输入图像(Groq 多模态)
import { groq } from '@ai-sdk/groq';
import { generateText } from 'ai';
const { text } = await generateText({
model: groq('meta-llama/llama-4-scout-17b-16e-instruct'), // Multi-modal model
messages: [
{
role: 'user',
content: [
{ type: 'text', text: 'What is in this image?' },
{ type: 'image', image: 'https://example.com/image.jpg' },
],
},
],
});
console.log(text);
Vercel AI Gateway
简介
通过单一 API 访问来自 20 多家 Provider(OpenAI、Anthropic、Google、Groq、xAI、Mistral 等)的模型的统一接口。需要 Vercel 账户和信用卡。
设置
AI_GATEWAY_API_KEY=your_gateway_api_key
在 Vercel Dashboard > AI Gateway 中获取密钥。
⚠️ 注意:使用 Gateway 需要信用卡。通过 Gateway 路由的模型调用将会产生费用。
身份验证
API 密钥身份验证
通过环境变量设置或直接在代码中设置:
import { createGateway } from 'ai';
const gateway = createGateway({
apiKey: process.env.AI_GATEWAY_API_KEY,
});
OIDC 身份验证(Vercel 部署)
部署到 Vercel 时,可使用 OIDC 令牌进行自动身份验证(无需 API 密钥):
生产/预览环境:自动处理 OIDC,无需设置。
本地开发:
- 安装并登录 Vercel CLI:
vercel login - 拉取 OIDC 令牌:
vercel env pull - 使用
vercel dev启动开发服务器(自动刷新令牌)
注意:OIDC 令牌在 12 小时后过期;使用 vercel dev 自动刷新,或手动再次运行 vercel env pull。
# Start dev with automatic token management
vercel dev
基本用法
import { generateText } from 'ai';
// Plain model string format: creator/model-name
const { text } = await generateText({
model: 'openai/gpt-5',
prompt: 'Explain quantum computing.',
});
console.log(text);
Gateway 实例
import { createGateway } from 'ai';
const gateway = createGateway({
apiKey: process.env.AI_GATEWAY_API_KEY,
});
const { text } = await generateText({
model: gateway('anthropic/claude-sonnet-4'),
prompt: 'Write a haiku about AI.',
});
console.log(text);
模型发现(动态)
import { gateway } from 'ai';
const availableModels = await gateway.getAvailableModels();
availableModels.models.forEach((model) => {
console.log(`${model.id}: ${model.name}`);
if (model.pricing) {
console.log(` Input: $${model.pricing.input}/token`);
console.log(` Output: $${model.pricing.output}/token`);
}
});
// Use first model
const { text } = await generateText({
model: availableModels.models[0].id,
prompt: 'Hello world',
});
检查额度使用情况
import { gateway } from 'ai';
const credits = await gateway.getCredits();
console.log(`Balance: ${credits.balance} credits`);
console.log(`Total used: ${credits.total_used} credits`);
使用 Gateway 进行流式生成
import { streamText } from 'ai';
const { textStream } = await streamText({
model: 'openai/gpt-5',
prompt: 'Explain serverless architecture.',
});
for await (const chunk of textStream) {
process.stdout.write(chunk);
}
使用 Gateway 调用工具
import { generateText, tool } from 'ai';
import { z } from 'zod';
const weatherTool = tool({
description: 'Get weather',
inputSchema: z.object({ location: z.string() }),
execute: async ({ location }) => `Sunny in ${location}`,
});
const { text } = await generateText({
model: 'xai/grok-4', // Via Gateway
prompt: 'What is the weather in SF?',
tools: { getWeather: weatherTool },
});
console.log(text);
使用自己的密钥(BYOK)
将自己的 Provider 凭据连接到 Gateway,以访问私有资源:
import { generateText } from 'ai';
import type { GatewayProviderOptions } from '@ai-sdk/gateway';
const { text } = await generateText({
model: 'anthropic/claude-sonnet-4',
prompt: 'Use my Anthropic account',
providerOptions: {
gateway: {
byok: {
anthropic: [{ apiKey: 'sk-ant-...' }],
},
} satisfies GatewayProviderOptions,
},
});
在 Vercel 团队的 AI Gateway 设置中配置 BYOK 凭据;完成配置后无需更改代码。
由 Provider 执行的工具
有些 Provider 提供在服务端执行的工具(例如,OpenAI 网页搜索)。可通过导入该 Provider 经由 Gateway 使用:
import { generateText, stepCountIs } from 'ai';
import { openai } from '@ai-sdk/openai';
const result = await generateText({
model: 'openai/gpt-5-mini',
prompt: 'What is the Vercel AI Gateway?',
stopWhen: stepCountIs(10),
tools: {
web_search: openai.tools.webSearch({}),
},
});
console.log(result.text);
注意:需要账户专属配置的工具(例如,Claude Agent Skills)可能需要通过 BYOK 直接访问 Provider。
提供商路由与回退
核心路由选项:
order:按顺序尝试提供商(回退优先级)only:仅限指定的提供商models:主模型失败时回退到备用模型user:按最终用户跟踪用量tags:为请求分类以便分析zeroDataRetention:仅使用零数据保留的提供商byok:请求级别的 BYOK 凭证
示例:提供商与模型回退
import { generateText } from 'ai';
import type { GatewayProviderOptions } from '@ai-sdk/gateway';
const { text } = await generateText({
model: 'openai/gpt-4o', // Primary model
prompt: 'Write a TypeScript haiku',
providerOptions: {
gateway: {
order: ['vertex', 'anthropic'], // Try Vertex AI first, then Anthropic
only: ['vertex', 'anthropic'], // Only allow these providers
models: ['openai/gpt-5-nano', 'gemini-2.0-flash'], // Fallback models
user: 'user-123',
tags: ['code-gen', 'v2'],
} satisfies GatewayProviderOptions,
},
});
// Fallback sequence:
// 1. Try vertex with openai/gpt-4o
// 2. Try anthropic with openai/gpt-4o
// 3. Try vertex with openai/gpt-5-nano
// 4. Try anthropic with openai/gpt-5-nano
// etc.
示例:用量跟踪
import { generateText } from 'ai';
import type { GatewayProviderOptions } from '@ai-sdk/gateway';
const { text } = await generateText({
model: 'anthropic/claude-sonnet-4',
prompt: 'Summarize this document...',
providerOptions: {
gateway: {
user: 'user-abc-123', // Track per end-user
tags: ['document-summary', 'premium-feature'],
} satisfies GatewayProviderOptions,
},
});
// View analytics by user and feature in Vercel Dashboard
零数据保留
对于敏感数据,仅将请求路由到实行零数据保留政策的提供商:
import { generateText } from 'ai';
import type { GatewayProviderOptions } from '@ai-sdk/gateway';
const { text } = await generateText({
model: 'anthropic/claude-sonnet-4',
prompt: 'Process sensitive document...',
providerOptions: {
gateway: {
zeroDataRetention: true, // Enforce zero data retention
} satisfies GatewayProviderOptions,
},
});
当 zeroDataRetention: true 时,Gateway 仅将请求路由到不会保留你数据的提供商。省略此选项或设为 false 时,不会执行任何限制。
核心概念
Agent 的调用选项
在运行时动态配置 Agent:
import { ToolLoopAgent } from 'ai';
import { z } from 'zod';
const supportAgent = new ToolLoopAgent({
model: 'groq/llama-3.3-70b-versatile',
callOptionsSchema: z.object({
userId: z.string(),
accountType: z.enum(['free', 'pro', 'enterprise']),
}),
instructions: 'You are a support agent.',
prepareCall: ({ options, ...settings }) => ({
...settings,
instructions:
settings.instructions +
`\nUser: ${options.userId}, Account: ${options.accountType}`,
}),
});
const result = await supportAgent.generate({
prompt: 'How do I upgrade?',
options: {
userId: 'user-456',
accountType: 'free',
},
});
使用 React 集成 UI
import { createAgentUIStreamResponse } from 'ai';
import { useChat } from '@ai-sdk/react';
import { InferAgentUIMessage } from 'ai';
// Server-side
export async function POST(request: Request) {
const { messages } = await request.json();
return createAgentUIStreamResponse({
agent: weatherAgent,
messages,
});
}
// Client-side
type AgentMessage = InferAgentUIMessage<typeof weatherAgent>;
const { messages, sendMessage } = useChat<AgentMessage>();
最佳实践
Groq
- 使用
llama-3.3-70b-versatile,兼顾性能与成本。 - 对低延迟、轻量级任务使用
llama-3.1-8b-instant。 - 启用
parallelToolCalls: true(默认值),以加快多工具并行执行。 - 如果可以接受偶尔失败,请使用
serviceTier: 'flex',以获得 10 倍速率限制。
Vercel AI Gateway
- 务必添加信用卡;Gateway 按 Token 收费。
- 使用
only/order控制路由和成本。 - 使用
user和tags跟踪支出并进行调试。 - 对敏感数据启用
zeroDataRetention。 - 定期检查
gateway.getCredits()以监控用量。
Agent
- 从
ToolLoopAgent开始,仅在需要时扩展。 - 结合结构化输出与工具调用,以获得丰富的响应。
- 对支付/删除操作使用工具审批。
- 设置
stopWhen以控制循环迭代次数(默认值:stepCountIs(20))。
常见模式
RAG Agent
const ragAgent = new ToolLoopAgent({
model: 'groq/llama-3.3-70b-versatile',
tools: {
searchDocs: tool({
description: 'Search documentation',
inputSchema: z.object({ query: z.string() }),
execute: async ({ query }) => {
// Call vector DB (Upstash, Pinecone, etc.)
return { docs: [/* ... */] };
},
}),
},
instructions: 'Answer questions by searching docs.',
});
多提供商回退
const { text } = await generateText({
model: 'anthropic/claude-sonnet-4',
prompt: 'Complex task requiring reasoning',
providerOptions: {
gateway: {
models: ['openai/gpt-5', 'gemini-2.0-flash'],
},
},
});
成本优化选择
const isSensitive = userQuery.includes('payment');
const model = isSensitive
? 'anthropic/claude-sonnet-4'
: 'openai/gpt-5-nano';
const { text } = await generateText({
model,
prompt: userQuery,
});
时间线
- AI SDK 6 Beta:现已推出(固定版本)
- 稳定版发布:2025 年底