ai-sdk-core
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAI SDK Core
AI SDK Core
Production-ready backend AI with Vercel AI SDK v5.
Last Updated: 2025-11-21
基于Vercel AI SDK v5的生产级后端AI解决方案。
最后更新时间:2025-11-21
Table of Contents
目录
Quick Start (5 Minutes)
快速开始(5分钟)
Installation
安装
bash
bun add ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google workers-ai-provider zod # preferredbash
bun add ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google workers-ai-provider zod # 推荐方式or: npm install ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google workers-ai-provider zod
或使用npm安装:npm install ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google workers-ai-provider zod
undefinedundefinedEnvironment Variables
环境变量
bash
undefinedbash
undefined.env
.env
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_GENERATIVE_AI_API_KEY=...
undefinedOPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_GENERATIVE_AI_API_KEY=...
undefinedFirst Example: Generate Text
第一个示例:生成文本
typescript
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const result = await generateText({
model: openai('gpt-4-turbo'),
prompt: 'What is TypeScript?',
});
console.log(result.text);typescript
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const result = await generateText({
model: openai('gpt-4-turbo'),
prompt: 'What is TypeScript?',
});
console.log(result.text);First Example: Streaming Chat
第一个示例:流式聊天
typescript
import { streamText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
const stream = streamText({
model: anthropic('claude-sonnet-4-5-20250929'),
messages: [
{ role: 'user', content: 'Tell me a story' },
],
});
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}typescript
import { streamText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
const stream = streamText({
model: anthropic('claude-sonnet-4-5-20250929'),
messages: [
{ role: 'user', content: 'Tell me a story' },
],
});
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}First Example: Structured Output
第一个示例:结构化输出
typescript
import { generateObject } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const result = await generateObject({
model: openai('gpt-4'),
schema: z.object({
name: z.string(),
age: z.number(),
skills: z.array(z.string()),
}),
prompt: 'Generate a person profile for a software engineer',
});
console.log(result.object);
// { name: "Alice", age: 28, skills: ["TypeScript", "React"] }typescript
import { generateObject } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const result = await generateObject({
model: openai('gpt-4'),
schema: z.object({
name: z.string(),
age: z.number(),
skills: z.array(z.string()),
}),
prompt: 'Generate a person profile for a software engineer',
});
console.log(result.object);
// { name: "Alice", age: 28, skills: ["TypeScript", "React"] }Secure Installation
安全安装
This installs 6+ AI provider packages simultaneously — a large dependency surface to audit. Before installing, follow supply chain security best practices:
- Block post-install scripts — (or Bun: disabled by default)
npm config set ignore-scripts true - Cooldown period — Wait 7 days for new package versions to be vetted by the community
- Audit before installing — Run or use
socket package score npm <pkg>to check packagessocket npm install <pkg>
Load the skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement.
dependency-upgrade此命令会同时安装6+个AI供应商包,依赖面较广需要审核。安装前请遵循供应链安全最佳实践:
- 阻止安装后脚本 — (Bun默认已禁用)
npm config set ignore-scripts true - 冷却期 — 等待7天,让社区验证新版本包的安全性
- 安装前审核 — 运行或使用
socket package score npm <pkg>检查包安全性socket npm install <pkg>
加载技能以获取完整安全配置,包括Socket CLI集成、冷却期设置、锁文件验证和CI强制执行。
dependency-upgradeCore Functions
核心功能
Load for complete API reference of all 4 core functions.
references/core-functions.md加载获取所有4个核心函数的完整API参考
references/core-functions.mdQuick Overview
快速概览
AI SDK v5 provides 4 core functions:
| Function | Output | Streaming | Use Case |
|---|---|---|---|
| Text | No | Batch processing, simple completions |
| Text | Yes | Chat UIs, long responses |
| Structured | No | Data extraction, JSON generation |
| Structured | Yes | Real-time forms, progressive UIs |
AI SDK v5提供4个核心函数:
| 函数 | 输出类型 | 是否支持流式 | 使用场景 |
|---|---|---|---|
| 文本 | 否 | 批量处理、简单补全 |
| 文本 | 是 | 聊天UI、长文本响应 |
| 结构化数据 | 否 | 数据提取、JSON生成 |
| 结构化数据 | 是 | 实时表单、渐进式UI |
Basic Example
基础示例
typescript
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const result = await generateText({
model: openai('gpt-4-turbo'),
prompt: 'Explain quantum computing',
});
console.log(result.text);→ Load for: Complete signatures, tool usage patterns, error handling, streaming examples, comparison table
references/core-functions.mdtypescript
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const result = await generateText({
model: openai('gpt-4-turbo'),
prompt: 'Explain quantum computing',
});
console.log(result.text);→ 加载获取: 完整签名、工具使用模式、错误处理、流式示例、对比表
references/core-functions.mdProvider Setup & Configuration
供应商设置与配置
Load for complete setup instructions for all providers.
references/provider-setup.md加载获取所有供应商的完整设置说明
references/provider-setup.mdQuick Overview
快速概览
AI SDK v5 supports 4 major providers:
| Provider | Environment Variable | Latest Models |
|---|---|---|
| OpenAI | | GPT-5, GPT-4 Turbo |
| Anthropic | | Claude Sonnet 4.5, Opus 4 |
| Gemini 2.5 Pro/Flash | |
| Cloudflare | Workers AI binding | Llama 3.1, Qwen 2.5 |
AI SDK v5支持4大主流供应商:
| 供应商 | 环境变量 | 最新模型 |
|---|---|---|
| OpenAI | | GPT-5、GPT-4 Turbo |
| Anthropic | | Claude Sonnet 4.5、Opus 4 |
| Gemini 2.5 Pro/Flash | |
| Cloudflare | Workers AI绑定 | Llama 3.1、Qwen 2.5 |
Basic Setup
基础设置
typescript
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
// API key from environment
const result = await generateText({
model: openai('gpt-4-turbo'),
prompt: 'Hello',
});→ Load for: Complete API configuration, rate limiting, error handling, Cloudflare Workers optimization, model selection guides
references/provider-setup.mdtypescript
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
// 从环境变量获取API密钥
const result = await generateText({
model: openai('gpt-4-turbo'),
prompt: 'Hello',
});→ 加载获取: 完整API配置、速率限制、错误处理、Cloudflare Workers优化、模型选择指南
references/provider-setup.mdTool Calling & Agents
工具调用与Agent
Load for complete tool and agent documentation.
references/tools-and-agents.md加载获取完整的工具与Agent文档
references/tools-and-agents.mdQuick Overview
快速概览
Tools allow models to call external functions. Agents manage multi-step workflows.
v5 Tool Changes:
- →
parameters(Zod schema)inputSchema - Tool properties: →
args,input→resultoutput - →
maxStepsstopWhen(stepCountIs(n))
工具允许模型调用外部函数,Agent用于管理多步骤工作流。
v5版本工具变更:
- →
parameters(Zod schema)inputSchema - 工具属性:→
args,input→resultoutput - →
maxStepsstopWhen(stepCountIs(n))
Basic Tool Example
基础工具示例
typescript
import { generateText, tool } from 'ai';
import { z } from 'zod';
const result = await generateText({
model: openai('gpt-4'),
tools: {
weather: tool({
description: 'Get weather for a location',
inputSchema: z.object({ location: z.string() }),
execute: async ({ location }) => {
return { temperature: 72, condition: 'sunny' };
},
}),
},
prompt: 'What is the weather in Tokyo?',
});→ Load for: Agent class usage, multi-step execution, dynamic tools, stop conditions
references/tools-and-agents.mdtypescript
import { generateText, tool } from 'ai';
import { z } from 'zod';
const result = await generateText({
model: openai('gpt-4'),
tools: {
weather: tool({
description: 'Get weather for a location',
inputSchema: z.object({ location: z.string() }),
execute: async ({ location }) => {
return { temperature: 72, condition: 'sunny' };
},
}),
},
prompt: 'What is the weather in Tokyo?',
});→ 加载获取: Agent类使用方法、多步骤执行、动态工具、停止条件
references/tools-and-agents.mdCritical v4→v5 Migration
重要v4→v5迁移指南
Load for complete migration guide.
references/v4-to-v5-migration.md加载获取完整迁移指南
references/v4-to-v5-migration.mdKey Breaking Changes
关键破坏性变更
AI SDK v5 has 9 major breaking changes:
- →
maxTokensmaxOutputTokens - →
parameters(Zod)inputSchema - →
maxStepsstopWhen(stepCountIs(n)) - →
CoreMessageModelMessage - Package reorganization (→
ai/rsc)@ai-sdk/rsc
AI SDK v5有9大破坏性变更:
- →
maxTokensmaxOutputTokens - →
parameters(Zod)inputSchema - →
maxStepsstopWhen(stepCountIs(n)) - →
CoreMessageModelMessage - 包重组(→
ai/rsc)@ai-sdk/rsc
Automated Migration
自动化迁移
bash
bunx ai migrate # Auto-migrates most changes→ Load for: Complete breaking changes list, migration examples, checklist, official migration guide link
references/v4-to-v5-migration.mdbash
bunx ai migrate # 自动迁移大部分变更→ 加载获取: 完整破坏性变更列表、迁移示例、检查清单、官方迁移指南链接
references/v4-to-v5-migration.mdTop 12 Errors & Solutions
12大常见错误与解决方案
1. AI_APICallError
1. AI_APICallError
Cause: API request failed (network, auth, rate limit).
Solution:
typescript
import { AI_APICallError } from 'ai';
try {
const result = await generateText({
model: openai('gpt-4'),
prompt: 'Hello',
});
} catch (error) {
if (error instanceof AI_APICallError) {
console.error('API call failed:', error.message);
console.error('Status code:', error.statusCode);
console.error('Response:', error.responseBody);
// Check common causes
if (error.statusCode === 401) {
// Invalid API key
} else if (error.statusCode === 429) {
// Rate limit - implement backoff
} else if (error.statusCode >= 500) {
// Provider issue - retry
}
}
}Prevention:
- Validate API keys at startup
- Implement retry logic with exponential backoff
- Monitor rate limits
- Handle network errors gracefully
原因: API请求失败(网络问题、认证错误、速率限制)。
解决方案:
typescript
import { AI_APICallError } from 'ai';
try {
const result = await generateText({
model: openai('gpt-4'),
prompt: 'Hello',
});
} catch (error) {
if (error instanceof AI_APICallError) {
console.error('API调用失败:', error.message);
console.error('状态码:', error.statusCode);
console.error('响应内容:', error.responseBody);
// 检查常见原因
if (error.statusCode === 401) {
// API密钥无效
} else if (error.statusCode === 429) {
// 速率限制 - 实现退避策略
} else if (error.statusCode >= 500) {
// 供应商服务问题 - 重试请求
}
}
}预防措施:
- 在启动时验证API密钥
- 实现带指数退避的重试逻辑
- 监控速率限制
- 优雅处理网络错误
2. AI_NoObjectGeneratedError
2. AI_NoObjectGeneratedError
Cause: Model didn't generate valid object matching schema.
Solution:
typescript
import { AI_NoObjectGeneratedError } from 'ai';
try {
const result = await generateObject({
model: openai('gpt-4'),
schema: z.object({ /* complex schema */ }),
prompt: 'Generate data',
});
} catch (error) {
if (error instanceof AI_NoObjectGeneratedError) {
console.error('No valid object generated');
// Solutions:
// 1. Simplify schema
// 2. Add more context to prompt
// 3. Provide examples in prompt
// 4. Try different model (gpt-4 better than gpt-3.5 for complex objects)
}
}Prevention:
- Start with simple schemas, add complexity incrementally
- Include examples in prompt: "Generate a person like: { name: 'Alice', age: 30 }"
- Use GPT-4 for complex structured output
- Test schemas with sample data first
原因: 模型未生成符合schema的有效对象。
解决方案:
typescript
import { AI_NoObjectGeneratedError } from 'ai';
try {
const result = await generateObject({
model: openai('gpt-4'),
schema: z.object({ /* 复杂schema */ }),
prompt: 'Generate data',
});
} catch (error) {
if (error instanceof AI_NoObjectGeneratedError) {
console.error('未生成有效对象');
// 解决方法:
// 1. 简化schema
// 2. 在提示词中添加更多上下文
// 3. 在提示词中提供示例
// 4. 尝试使用不同模型(gpt-4处理复杂对象优于gpt-3.5)
}
}预防措施:
- 从简单schema开始,逐步增加复杂度
- 在提示词中包含示例:"生成如下格式的人物信息:{ name: 'Alice', age: 30 }"
- 使用GPT-4处理复杂结构化输出
- 先使用样本数据测试schema
3. Worker Startup Limit (270ms+)
3. Worker启动超时(270ms+)
Cause: AI SDK v5 + Zod initialization overhead in Cloudflare Workers exceeds startup limits.
Solution:
typescript
// BAD: Top-level imports cause startup overhead
import { createWorkersAI } from 'workers-ai-provider';
import { complexSchema } from './schemas';
const workersai = createWorkersAI({ binding: env.AI });
// GOOD: Lazy initialization inside handler
export default {
async fetch(request, env) {
const { createWorkersAI } = await import('workers-ai-provider');
const workersai = createWorkersAI({ binding: env.AI });
// Use workersai here
}
}Prevention:
- Move AI SDK imports inside route handlers
- Minimize top-level Zod schemas
- Monitor Worker startup time (must be <400ms)
- Use Wrangler's startup time reporting
GitHub Issue: Search for "Workers startup limit" in Vercel AI SDK issues
→ Load for errors #4-#12 with complete solutions.
references/error-catalog.mdRemaining 9 errors:
4. streamText Fails Silently (RESOLVED in v4.1.22)
5. AI_LoadAPIKeyError
6. AI_InvalidArgumentError
7. AI_NoContentGeneratedError
8. AI_TypeValidationError
9. AI_RetryError
10. Rate Limiting Errors
11. TypeScript Performance with Zod
12. Invalid JSON Response (Provider-Specific)
For complete error catalog:
See complete error reference at https://ai-sdk.dev/docs/reference/ai-sdk-errors
原因: Cloudflare Workers中AI SDK v5 + Zod初始化开销超过启动限制。
解决方案:
typescript
// 错误写法:顶层导入会导致启动开销
import { createWorkersAI } from 'workers-ai-provider';
import { complexSchema } from './schemas';
const workersai = createWorkersAI({ binding: env.AI });
// 正确写法:在处理器内部延迟初始化
export default {
async fetch(request, env) {
const { createWorkersAI } = await import('workers-ai-provider');
const workersai = createWorkersAI({ binding: env.AI });
// 在此处使用workersai
}
}预防措施:
- 将AI SDK导入移至路由处理器内部
- 减少顶层Zod schema数量
- 监控Worker启动时间(必须<400ms)
- 使用Wrangler的启动时间报告功能
GitHub Issue: 在Vercel AI SDK issues中搜索"Workers startup limit"
→ 加载获取错误#4-#12的完整解决方案
references/error-catalog.md剩余9个错误:
4. streamText静默失败(已在v4.1.22修复)
5. AI_LoadAPIKeyError
6. AI_InvalidArgumentError
7. AI_NoContentGeneratedError
8. AI_TypeValidationError
9. AI_RetryError
10. 速率限制错误
11. Zod相关TypeScript性能问题
12. 无效JSON响应(供应商特定)
完整错误目录:
查看完整错误参考:https://ai-sdk.dev/docs/reference/ai-sdk-errors
Production Best Practices
生产环境最佳实践
Load for complete production deployment guide.
references/production-guide.md加载获取完整生产部署指南
references/production-guide.mdKey Categories
核心分类
- Performance: Streaming patterns, token limits, provider caching, Zod optimization
- Error Handling: try-catch patterns, retry logic, proper logging
- Cost Optimization: Model selection, token limits, response caching
- Cloudflare Workers: Lazy imports, startup monitoring, streaming responses
- Next.js/Vercel: Server Actions, Server Components, loading states
- 性能优化:流式处理模式、令牌限制、供应商缓存、Zod优化
- 错误处理:try-catch模式、重试逻辑、正确日志记录
- 成本优化:模型选择、令牌限制、响应缓存
- Cloudflare Workers:延迟导入、启动监控、流式响应
- Next.js/Vercel:Server Actions、Server Components、加载状态
Quick Example
快速示例
typescript
// Use streaming for user-facing responses
const stream = streamText({
model: openai('gpt-4'),
prompt: 'Long essay',
maxOutputTokens: 500,
maxRetries: 3,
});
return stream.toDataStreamResponse();→ Load for: Platform-specific patterns, deployment checklists, optimization strategies
references/production-guide.mdtypescript
// 面向用户的响应使用流式处理
const stream = streamText({
model: openai('gpt-4'),
prompt: 'Long essay',
maxOutputTokens: 500,
maxRetries: 3,
});
return stream.toDataStreamResponse();→ 加载获取: 平台特定模式、部署检查清单、优化策略
references/production-guide.mdWhen to Load References
何时加载参考文档
Load when:
references/core-functions.md- User needs complete API documentation for generateText, streamText, generateObject, or streamObject
- Questions about function signatures, parameters, or return types
- Need detailed tool usage patterns or streaming examples
- Troubleshooting function-specific errors
Load when:
references/provider-setup.md- Setting up OpenAI, Anthropic, Google, or Cloudflare Workers AI
- Configuring API keys or environment variables
- Troubleshooting provider-specific errors (rate limits, authentication)
- Questions about model selection or best practices for each provider
- Cloudflare Workers startup optimization needed
Load when:
references/tools-and-agents.md- Implementing tool calling or agent workflows
- Questions about Agent class vs raw generateText
- Setting up multi-step execution with stopWhen
- Dynamic tools or complex agentic patterns
Load when:
references/v4-to-v5-migration.md- Migrating existing v4 codebase to v5
- Questions about breaking changes
- Need migration examples or automated migration tool
- Troubleshooting migration-related errors
Load when:
references/error-catalog.md- User encounters any of the 12 common errors (beyond top 3 shown inline)
- Need complete error solutions with code examples
- Troubleshooting production errors
- Questions about error prevention strategies
Load when:
references/production-guide.md- Deploying to production (any platform)
- Performance optimization needed
- Cost optimization questions
- Platform-specific patterns (Cloudflare Workers, Next.js/Vercel)
- Error handling or logging strategies
当以下情况时加载:
references/core-functions.md- 需要generateText、streamText、generateObject或streamObject的完整API文档
- 有关于函数签名、参数或返回类型的疑问
- 需要详细的工具使用模式或流式示例
- 排查特定函数相关的错误
当以下情况时加载:
references/provider-setup.md- 设置OpenAI、Anthropic、Google或Cloudflare Workers AI
- 配置API密钥或环境变量
- 排查供应商特定错误(速率限制、认证问题)
- 有关于模型选择或各供应商最佳实践的疑问
- 需要Cloudflare Workers启动优化方案
当以下情况时加载:
references/tools-and-agents.md- 实现工具调用或Agent工作流
- 有关于Agent类与原生generateText对比的疑问
- 设置带stopWhen的多步骤执行
- 动态工具或复杂Agent模式
当以下情况时加载:
references/v4-to-v5-migration.md- 将现有v4代码库迁移至v5
- 有关于破坏性变更的疑问
- 需要迁移示例或自动化迁移工具
- 排查迁移相关错误
当以下情况时加载:
references/error-catalog.md- 遇到12种常见错误中的任意一种(除了上面展示的前3种)
- 需要完整的错误解决方案及代码示例
- 排查生产环境错误
- 有关于错误预防策略的疑问
当以下情况时加载:
references/production-guide.md- 部署至生产环境(任意平台)
- 需要性能优化方案
- 有关于成本优化的疑问
- 平台特定模式(Cloudflare Workers、Next.js/Vercel)
- 错误处理或日志记录策略
When to Use This Skill
何时使用本技能
Use ai-sdk-core when:
适合使用ai-sdk-core的场景:
- Building backend AI features (server-side text generation)
- Implementing server-side text generation (Node.js, Workers, Next.js)
- Creating structured AI outputs (JSON, forms, data extraction)
- Building AI agents with tools (multi-step workflows)
- Integrating multiple AI providers (OpenAI, Anthropic, Google, Cloudflare)
- Migrating from AI SDK v4 to v5
- Encountering AI SDK errors (AI_APICallError, AI_NoObjectGeneratedError, etc.)
- Using AI in Cloudflare Workers (with workers-ai-provider)
- Using AI in Next.js Server Components/Actions
- Need consistent API across different LLM providers
- 构建后端AI功能(服务端文本生成)
- 实现服务端文本生成(Node.js、Workers、Next.js)
- 创建结构化AI输出(JSON、表单、数据提取)
- 构建带工具的AI Agent(多步骤工作流)
- 集成多个AI供应商(OpenAI、Anthropic、Google、Cloudflare)
- 从AI SDK v4迁移至v5
- 遇到AI SDK错误(AI_APICallError、AI_NoObjectGeneratedError等)
- 在Cloudflare Workers中使用AI(搭配workers-ai-provider)
- 在Next.js Server Components/Actions中使用AI
- 需要跨不同LLM供应商的统一API
Don't use this skill when:
不适合使用本技能的场景:
- Building React chat UIs (use ai-sdk-ui skill instead)
- Need frontend hooks like useChat (use ai-sdk-ui skill instead)
- Need advanced topics like embeddings or image generation (check official docs)
- Building native Cloudflare Workers AI apps without multi-provider (use cloudflare-workers-ai skill instead)
- Need Generative UI / RSC (see https://ai-sdk.dev/docs/ai-sdk-rsc)
- 构建React聊天UI(请使用ai-sdk-ui技能)
- 需要useChat等前端钩子(请使用ai-sdk-ui技能)
- 需要嵌入或图像生成等高级功能(请查看官方文档)
- 构建无需多供应商的原生Cloudflare Workers AI应用(请使用cloudflare-workers-ai技能)
- 需要生成式UI / RSC(查看https://ai-sdk.dev/docs/ai-sdk-rsc)
Dependencies & Versions
依赖与版本
json
{
"dependencies": {
"ai": "^5.0.116",
"@ai-sdk/openai": "^2.0.88",
"@ai-sdk/anthropic": "^2.0.56",
"@ai-sdk/google": "^2.0.51",
"workers-ai-provider": "^2.0.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/node": "^24.10.1",
"typescript": "^5.9.3"
}
}Version Notes:
- AI SDK v5.0.116+ (stable, latest as of December 2025)
- v6 is in beta - not covered in this skill
- Zod compatibility: This skill uses Zod 3.x, but AI SDK 5 officially supports both Zod 3.x and Zod 4.x (4.1.12 latest)
- Zod 4 recommended for new projects (released August 2025)
- Zod 4 has breaking changes: error APIs, behavior,
.default()removedZodError.errors - Some peer dependency warnings may occur with when using Zod 4
zod-to-json-schema - See https://zod.dev/v4/changelog for migration guide
- Provider packages at 2.0+ for v5 compatibility
Check Latest Versions:
bash
npm view ai version
npm view @ai-sdk/openai version
npm view @ai-sdk/anthropic version
npm view @ai-sdk/google version
npm view workers-ai-provider version
npm view zod version # Check for Zod 4.x updatesjson
{
"dependencies": {
"ai": "^5.0.116",
"@ai-sdk/openai": "^2.0.88",
"@ai-sdk/anthropic": "^2.0.56",
"@ai-sdk/google": "^2.0.51",
"workers-ai-provider": "^2.0.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/node": "^24.10.1",
"typescript": "^5.9.3"
}
}版本说明:
- AI SDK v5.0.116+(稳定版,截至2025年12月为最新版本)
- v6处于测试阶段 - 本技能不包含相关内容
- Zod兼容性:本技能使用Zod 3.x,但AI SDK 5官方同时支持Zod 3.x和Zod 4.x(最新版4.1.12)
- 新项目推荐使用Zod 4(2025年8月发布)
- Zod 4存在破坏性变更:错误API、行为、
.default()移除ZodError.errors - 使用Zod 4时,可能会出现一些对等依赖警告
zod-to-json-schema - 查看https://zod.dev/v4/changelog获取迁移指南
- 供应商包版本需为2.0+以兼容v5
检查最新版本:
bash
npm view ai version
npm view @ai-sdk/openai version
npm view @ai-sdk/anthropic version
npm view @ai-sdk/google version
npm view workers-ai-provider version
npm view zod version # 检查Zod 4.x更新Links to Official Documentation
官方文档链接
Core Documentation
核心文档
- AI SDK Introduction: https://ai-sdk.dev/docs/introduction
- AI SDK Core Overview: https://ai-sdk.dev/docs/ai-sdk-core/overview
- Generating Text: https://ai-sdk.dev/docs/ai-sdk-core/generating-text
- Generating Structured Data: https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data
- Tools and Tool Calling: https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
- Agents Overview: https://ai-sdk.dev/docs/agents/overview
- Foundations: https://ai-sdk.dev/docs/foundations/overview
- AI SDK介绍: https://ai-sdk.dev/docs/introduction
- AI SDK Core概述: https://ai-sdk.dev/docs/ai-sdk-core/overview
- 文本生成: https://ai-sdk.dev/docs/ai-sdk-core/generating-text
- 结构化数据生成: https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data
- 工具与工具调用: https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
- Agent概述: https://ai-sdk.dev/docs/agents/overview
- 基础原理: https://ai-sdk.dev/docs/foundations/overview
Advanced Topics (Not Replicated in This Skill)
高级主题(本技能未覆盖)
- Embeddings: https://ai-sdk.dev/docs/ai-sdk-core/embeddings
- Image Generation: https://ai-sdk.dev/docs/ai-sdk-core/generating-images
- Transcription: https://ai-sdk.dev/docs/ai-sdk-core/generating-transcriptions
- Speech: https://ai-sdk.dev/docs/ai-sdk-core/generating-speech
- MCP Tools: https://ai-sdk.dev/docs/ai-sdk-core/mcp-tools
- Telemetry: https://ai-sdk.dev/docs/ai-sdk-core/telemetry
- Generative UI: https://ai-sdk.dev/docs/ai-sdk-rsc
- 嵌入: https://ai-sdk.dev/docs/ai-sdk-core/embeddings
- 图像生成: https://ai-sdk.dev/docs/ai-sdk-core/generating-images
- 转录: https://ai-sdk.dev/docs/ai-sdk-core/generating-transcriptions
- 语音生成: https://ai-sdk.dev/docs/ai-sdk-core/generating-speech
- MCP工具: https://ai-sdk.dev/docs/ai-sdk-core/mcp-tools
- 遥测: https://ai-sdk.dev/docs/ai-sdk-core/telemetry
- 生成式UI: https://ai-sdk.dev/docs/ai-sdk-rsc
Migration & Troubleshooting
迁移与故障排查
- v4→v5 Migration Guide: https://ai-sdk.dev/docs/migration-guides/migration-guide-5-0
- All Error Types (28 total): https://ai-sdk.dev/docs/reference/ai-sdk-errors
- Troubleshooting Guide: https://ai-sdk.dev/docs/troubleshooting
Provider Documentation
供应商文档
- OpenAI Provider: https://ai-sdk.dev/providers/ai-sdk-providers/openai
- Anthropic Provider: https://ai-sdk.dev/providers/ai-sdk-providers/anthropic
- Google Provider: https://ai-sdk.dev/providers/ai-sdk-providers/google
- All Providers (25+): https://ai-sdk.dev/providers/overview
- Community Providers: https://ai-sdk.dev/providers/community-providers
- OpenAI供应商: https://ai-sdk.dev/providers/ai-sdk-providers/openai
- Anthropic供应商: https://ai-sdk.dev/providers/ai-sdk-providers/anthropic
- Google供应商: https://ai-sdk.dev/providers/ai-sdk-providers/google
- 所有供应商(25+): https://ai-sdk.dev/providers/overview
- 社区供应商: https://ai-sdk.dev/providers/community-providers
Cloudflare Integration
Cloudflare集成
- Workers AI Provider (Community): https://ai-sdk.dev/providers/community-providers/cloudflare-workers-ai
- Cloudflare Workers AI Docs: https://developers.cloudflare.com/workers-ai/
- workers-ai-provider GitHub: https://github.com/cloudflare/ai/tree/main/packages/workers-ai-provider
- Cloudflare AI SDK Configuration: https://developers.cloudflare.com/workers-ai/configuration/ai-sdk/
- Workers AI供应商(社区): https://ai-sdk.dev/providers/community-providers/cloudflare-workers-ai
- Cloudflare Workers AI文档: https://developers.cloudflare.com/workers-ai/
- workers-ai-provider GitHub: https://github.com/cloudflare/ai/tree/main/packages/workers-ai-provider
- Cloudflare AI SDK配置: https://developers.cloudflare.com/workers-ai/configuration/ai-sdk/
Vercel / Next.js Integration
Vercel / Next.js集成
- Vercel AI SDK 5.0 Blog: https://vercel.com/blog/ai-sdk-5
- Next.js App Router Integration: https://ai-sdk.dev/docs/getting-started/nextjs-app-router
- Next.js Pages Router Integration: https://ai-sdk.dev/docs/getting-started/nextjs-pages-router
- Vercel Functions: https://vercel.com/docs/functions
- Vercel Streaming: https://vercel.com/docs/functions/streaming
- Vercel AI SDK 5.0博客: https://vercel.com/blog/ai-sdk-5
- Next.js App Router集成: https://ai-sdk.dev/docs/getting-started/nextjs-app-router
- Next.js Pages Router集成: https://ai-sdk.dev/docs/getting-started/nextjs-pages-router
- Vercel Functions: https://vercel.com/docs/functions
- Vercel流式处理: https://vercel.com/docs/functions/streaming
GitHub & Community
GitHub与社区
- GitHub Repository: https://github.com/vercel/ai
- GitHub Issues: https://github.com/vercel/ai/issues
- Discord Community: https://discord.gg/vercel
- GitHub仓库: https://github.com/vercel/ai
- GitHub Issues: https://github.com/vercel/ai/issues
- Discord社区: https://discord.gg/vercel
Templates & References
模板与参考资源
This skill includes:
- 13 Templates: Ready-to-use code examples in
templates/ - 5 Reference Docs: Detailed guides in
references/ - 1 Script: Version checker in
scripts/
All files are optimized for copy-paste into your project.
Last Updated: 2025-12-22
Skill Version: 1.1.0
AI SDK Version: 5.0.116+
本技能包含:
- 13个模板: 目录下的即用型代码示例
templates/ - 5份参考文档: 目录下的详细指南
references/ - 1个脚本: 目录下的版本检查工具
scripts/
所有文件均已优化,可直接复制粘贴到项目中使用。
最后更新时间: 2025-12-22
技能版本: 1.1.0
AI SDK版本: 5.0.116+