mcpField
A
ai-sdk-core

ai-sdk-core

github.com/jezweb开发1.1k479 次安装3 周前更新
代码仓库

关于 ai-sdk-core

AI SDK Core 是用于构建后端大模型应用的 TypeScript 工具包,支持模型、工具及多模态能力。它涵盖 Agent 执行、结构化输出、模型提供方集成和 MCP 客户端支持。

主要功能

  1. 01文本生成与流式输出
  2. 02基于 Schema 的结构化输出
  3. 03Agent 与工具循环执行
  4. 04工具执行审批控制
  5. 05多模态生成与嵌入
  6. 06通过 MCP 客户端获取工具

适用场景

  1. 01构建后端大模型功能
  2. 02创建可调用工具的 Agent
  3. 03生成类型化 JSON 响应
  4. 04将 MCP 工具接入应用

MCP 相关

它提供 MCP 客户端接口,可通过 stdio 连接 MCP 服务并获取供应用使用的工具。README 也说明了动态 MCP 工具定义的安全注意事项。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jezweb/claude-skills --skill ai-sdk-core

安装后在 Claude Code 中输入/ai-sdk-core确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
VERIFICATION_REPORT.md
.claude-plugin/
plugin.json
references/
links-to-official-docs.md
production-patterns.md
providers-quickstart.md
top-errors.md
v5-breaking-changes.md
rules/
ai-sdk-core.md
scripts/
check-versions.sh
templates/
agent-with-tools.ts
anthropic-setup.ts
cloudflare-worker-integration.ts
generate-object-zod.ts
generate-text-basic.ts
google-setup.ts
multi-step-execution.ts
nextjs-server-action.ts
openai-setup.ts
package.json
stream-object-zod.ts
stream-text-chat.ts
tools-basic.ts

详细介绍

AI SDK Core

使用 Vercel AI SDK v5 和 v6 构建后端 AI。

安装:

npm install ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google zod

AI SDK 6(稳定版 - 2026 年 1 月)

**状态:**稳定 **最新版本:**[email protected](2026 年 1 月)

重大变更:Output API 取代 generateObject/streamObject

⚠️ 重要:generateObject() 和 streamObject() 已弃用,并将在未来版本中移除。请改用新的 Output API。

之前(v5 - 已弃用):

// ❌ DEPRECATED - will be removed
import { generateObject } from 'ai';

const result = await generateObject({
  model: openai('gpt-5'),
  schema: z.object({ name: z.string(), age: z.number() }),
  prompt: 'Generate a person',
});

之后(v6 - 请使用):

// ✅ NEW OUTPUT API
import { generateText, Output } from 'ai';

const result = await generateText({
  model: openai('gpt-5'),
  output: Output.object({ schema: z.object({ name: z.string(), age: z.number() }) }),
  prompt: 'Generate a person',
});

// Access the typed object
console.log(result.object); // { name: "Alice", age: 30 }
Output 类型
import { generateText, Output } from 'ai';

// Object with Zod schema
output: Output.object({ schema: myZodSchema })

// Array of typed objects
output: Output.array({ schema: personSchema })

// Enum/choice from options
output: Output.choice({ choices: ['positive', 'negative', 'neutral'] })

// Plain text (explicit)
output: Output.text()

// Unstructured JSON (no schema validation)
output: Output.json()
使用 Output API 进行流式处理
import { streamText, Output } from 'ai';

const result = streamText({
  model: openai('gpt-5'),
  output: Output.object({ schema: personSchema }),
  prompt: 'Generate a person',
});

// Stream partial objects
for await (const partialObject of result.objectStream) {
  console.log(partialObject); // { name: "Ali..." } -> { name: "Alice", age: ... }
}

// Get final object
const finalObject = await result.object;
v6 新功能

1. Agent 抽象 使用 ToolLoopAgent 类构建 Agent 的统一接口:

  • 全面控制执行流程、工具循环和状态管理
  • 取代手动编排工具调用

2. 工具执行审批(人在回路中)

使用选择性审批,改善用户体验。并非每次工具调用都需要审批。

tools: {
  payment: tool({
    // Dynamic approval based on input
    needsApproval: async ({ amount }) => amount > 1000,
    inputSchema: z.object({ amount: z.number() }),
    execute: async ({ amount }) => { /* process payment */ },
  }),

  readFile: tool({
    needsApproval: false, // Safe operations don't need approval
    inputSchema: z.object({ path: z.string() }),
    execute: async ({ path }) => fs.readFile(path),
  }),

  deleteFile: tool({
    needsApproval: true, // Destructive operations always need approval
    inputSchema: z.object({ path: z.string() }),
    execute: async ({ path }) => fs.unlink(path),
  }),
}

最佳实践:

  • 对于风险取决于参数的操作(例如支付金额),使用动态审批
  • 对于破坏性操作(删除、修改、购买),始终要求审批
  • 对于安全的读取操作,无需要求审批
  • 添加系统指令:“工具执行未获批准时,不要重试”
  • 为审批请求设置超时,避免状态卡住
  • 保存用户的重复操作偏好

来源:

3. 用于 RAG 的重排序

import { rerank } from 'ai';

const result = await rerank({
  model: cohere.reranker('rerank-v3.5'),
  query: 'user question',
  documents: searchResults,
  topK: 5,
});

4. MCP 工具(模型上下文协议)

⚠️ 安全警告:MCP 工具在生产环境中存在重大风险。请参阅下方的安全部分。

import { experimental_createMCPClient } from 'ai';

const mcpClient = await experimental_createMCPClient({
  transport: { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem'] },
});

const tools = await mcpClient.tools();

const result = await generateText({
  model: openai('gpt-5'),
  tools,
  prompt: 'List files in the current directory',
});

已知问题:MCP 工具可能无法在流式模式下执行(Vercel 社区讨论)。使用 generateText() 代替 streamText() 来处理 MCP 工具。

MCP 安全注意事项

⚠️ 重要:在生产环境中使用动态 MCP 工具存在安全风险:

风险:

  • 工具定义会成为 Agent 提示词的一部分
  • 工具定义可能在未发出警告的情况下意外更改
  • 遭到入侵的 MCP 服务可能注入恶意提示词
  • 新工具可能提升用户权限(例如,为只读服务添加删除功能)

解决方案 - 使用静态工具生成:

// ❌ RISKY: Dynamic tools change without your control
const mcpClient = await experimental_createMCPClient({ /* ... */ });
const tools = await mcpClient.tools(); // Can change anytime!

// ✅ SAFE: Generate static, versioned tool definitions
// Step 1: Install mcp-to-ai-sdk
npm install -g mcp-to-ai-sdk

// Step 2: Generate static tools (one-time, version controlled)
npx mcp-to-ai-sdk generate stdio 'npx -y @modelcontextprotocol/server-filesystem'

// Step 3: Import static tools
import { tools } from './generated-mcp-tools';

const result = await generateText({
  model: openai('gpt-5'),
  tools, // Static, reviewed, versioned
  prompt: 'Use tools',
});

最佳实践:生成静态工具,审核后提交至版本控制,并仅在有意更新时进行修改。

来源:Vercel 博客:MCP 安全

5. 语言模型中间件

import { wrapLanguageModel, extractReasoningMiddleware } from 'ai';

const wrappedModel = wrapLanguageModel({
  model: anthropic('claude-sonnet-4-5-20250929'),
  middleware: extractReasoningMiddleware({ tagName: 'think' }),
});

// Reasoning extracted automatically from <think>...</think> tags

6. 遥测(OpenTelemetry)

const result = await generateText({
  model: openai('gpt-5'),
  prompt: 'Hello',
  experimental_telemetry: {
    isEnabled: true,
    functionId: 'my-chat-function',
    metadata: { userId: '123' },
    recordInputs: true,
    recordOutputs: true,
  },
});

官方文档: https://ai-sdk.dev/docs


最新 AI 模型(2025-2026)

OpenAI

GPT-5.2(2025 年 12 月):

  • 400k 上下文窗口,128k 输出 token
  • 推理能力增强
  • 可通过 API 平台使用

GPT-5.1(2025 年 11 月):

  • 相较 GPT-5,速度和效率有所提升
  • 回复“更温暖”、更智能

GPT-5(2025 年 8 月):

  • 幻觉比 GPT-4o 减少 45%
  • 在数学、编码和视觉感知方面达到最先进水平

o3 推理模型(2025 年 12 月):

  • o3、o3-pro、o3-mini - 高级推理
  • o4-mini - 快速推理
import { openai } from '@ai-sdk/openai';
const gpt52 = openai('gpt-5.2');
const gpt51 = openai('gpt-5.1');
const gpt5 = openai('gpt-5');
const o3 = openai('o3');
const o3mini = openai('o3-mini');
Anthropic

Claude 4 系列(2025 年 5 月至 10 月):

  • Opus 4(5 月 22 日):最适合复杂推理,每百万 token 收费 $15/$75
  • Sonnet 4(5 月 22 日):性能均衡,每百万 token 收费 $3/$15
  • Opus 4.1(8 月 5 日):增强 Agent 任务和现实场景编码能力
  • Sonnet 4.5(9 月 29 日):在编码、Agent 和计算机使用方面能力最强
  • Haiku 4.5(10 月 15 日):小巧、快速、低延迟模型
import { anthropic } from '@ai-sdk/anthropic';
const sonnet45 = anthropic('claude-sonnet-4-5-20250929');  // Latest
const opus41 = anthropic('claude-opus-4-1-20250805');
const haiku45 = anthropic('claude-haiku-4-5-20251015');
Google

Gemini 2.5 系列(2025 年 3 月至 9 月):

  • Pro(2025 年 3 月):智能程度最高,发布时位列 LMArena 第 1 名
  • Pro Deep Think(2025 年 5 月):增强推理模式
  • Flash(2025 年 5 月):快速且经济高效
  • Flash-Lite(2025 年 9 月):效率优化版
import { google } from '@ai-sdk/google';
const pro = google('gemini-2.5-pro');
const flash = google('gemini-2.5-flash');
const lite = google('gemini-2.5-flash-lite');

核心功能

文本生成

generateText() - 使用工具进行文本补全
streamText() - 实时流式传输

结构化输出(v6 Output API)

Output.object() - 使用 Zod schema 定义类型化对象(替代 generateObject)
Output.array() - 类型化数组
Output.choice() - 枚举选择
Output.json() - 非结构化 JSON

用法示例请参见上文的“AI SDK 6”部分。

多模态功能
语音合成(文本转语音)
import { experimental_generateSpeech as generateSpeech } from 'ai';
import { openai } from '@ai-sdk/openai';

const result = await generateSpeech({
  model: openai.speech('tts-1-hd'),
  voice: 'alloy',
  text: 'Hello, how can I help you today?',
});

// result.audio is an ArrayBuffer containing the audio
const audioBuffer = result.audio;

支持的提供商:

  • OpenAI:tts-1、tts-1-hd、gpt-4o-mini-tts
  • ElevenLabs:eleven_multilingual_v2、eleven_turbo_v2
  • LMNT、Hume
转录(语音转文本)
import { experimental_transcribe as transcribe } from 'ai';
import { openai } from '@ai-sdk/openai';

const result = await transcribe({
  model: openai.transcription('whisper-1'),
  audio: audioFile, // File, Blob, ArrayBuffer, or URL
});

console.log(result.text); // Transcribed text
console.log(result.segments); // Timestamped segments

支持的提供商:

  • OpenAI:whisper-1
  • ElevenLabs、Deepgram、AssemblyAI、Groq、Rev.ai
图像生成
import { generateImage } from 'ai';
import { openai } from '@ai-sdk/openai';

const result = await generateImage({
  model: openai.image('dall-e-3'),
  prompt: 'A futuristic city at sunset',
  size: '1024x1024',
  n: 1,
});

// result.images is an array of generated images
const imageUrl = result.images[0].url;
const imageBase64 = result.images[0].base64;

支持的提供商:

  • OpenAI:dall-e-2、dall-e-3
  • Google:imagen-3.0
  • Fal AI、Black Forest Labs(Flux)、Luma AI、Replicate
嵌入
import { embed, embedMany, cosineSimilarity } from 'ai';
import { openai } from '@ai-sdk/openai';

// Single embedding
const result = await embed({
  model: openai.embedding('text-embedding-3-small'),
  value: 'Hello world',
});
console.log(result.embedding); // number[]

// Multiple embeddings (parallel processing)
const results = await embedMany({
  model: openai.embedding('text-embedding-3-small'),
  values: ['Hello', 'World', 'AI'],
  maxParallelCalls: 5, // Parallel processing
});

// Compare similarity
const similarity = cosineSimilarity(
  results.embeddings[0],
  results.embeddings[1]
);
console.log(`Similarity: ${similarity}`); // 0.0 to 1.0

支持的提供商:

  • OpenAI:text-embedding-3-small、text-embedding-3-large
  • Google:text-embedding-004
  • Cohere、Voyage AI、Mistral、Amazon Bedrock
多模态提示词(文件、图像、PDF)
import { generateText } from 'ai';
import { google } from '@ai-sdk/google';

const result = await generateText({
  model: google('gemini-2.5-pro'),
  messages: [{
    role: 'user',
    content: [
      { type: 'text', text: 'Summarize this document' },
      { type: 'file', data: pdfBuffer, mimeType: 'application/pdf' },
    ],
  }],
});

// Or with images
const result = await generateText({
  model: openai('gpt-5'),
  messages: [{
    role: 'user',
    content: [
      { type: 'text', text: 'What is in this image?' },
      { type: 'image', image: imageBuffer },
    ],
  }],
});

完整 API 请参阅官方文档:https://ai-sdk.dev/docs/ai-sdk-core


v5 流式响应方法

从 API 返回流式响应时,请使用正确的方法:

方法输出格式使用场景
toTextStreamResponse()纯文本块简单的文本流式传输
toUIMessageStreamResponse()包含 JSON 事件的 SSE聊天 UI(text-start、text-delta、text-end、finish)

对于聊天小组件和 UI,始终使用 toUIMessageStreamResponse():

const result = streamText({
  model: workersai('@cf/qwen/qwen3-30b-a3b-fp8'),
  messages,
  system: 'You are helpful.',
});

// ✅ For chat UIs - returns SSE with JSON events
return result.toUIMessageStreamResponse({
  headers: { 'Access-Control-Allow-Origin': '*' },
});

// ❌ For simple text - returns plain text chunks only
return result.toTextStreamResponse();

注意: AI SDK v5 中不存在 toDataStreamResponse()(这是常见误解)。


workers-ai-provider 版本兼容性

重要: [email protected] 需要 AI SDK v5,而非 v4。

# ✅ Correct - AI SDK v5 with workers-ai-provider v2
npm install ai@^5.0.0 workers-ai-provider@^2.0.0 zod@^3.25.0

# ❌ Wrong - AI SDK v4 causes error
npm install ai@^4.0.0 workers-ai-provider@^2.0.0
# Error: "AI SDK 4 only supports models that implement specification version v1"

Zod 版本: AI SDK v5 要求使用 zod@^3.25.0 或更高版本,以支持 zod/v3 和 zod/v4 导出。较旧版本(3.22.x)会导致构建错误:“Could not resolve zod/v4”。


Cloudflare Workers 启动修复

问题: AI SDK v5 + Zod 会导致启动时间超过 270 毫秒(超出 Workers 的 400 毫秒限制)。

解决方案:

// ❌ BAD: Top-level imports cause startup overhead
import { createWorkersAI } from 'workers-ai-provider';
const workersai = createWorkersAI({ binding: env.AI });

// ✅ GOOD: Lazy initialization inside handler
app.post('/chat', async (c) => {
  const { createWorkersAI } = await import('workers-ai-provider');
  const workersai = createWorkersAI({ binding: c.env.AI });
  // ...
});

其他建议:

  • 尽量减少顶层 Zod schema
  • 将复杂 schema 移入路由处理程序
  • 使用 Wrangler 监控启动时间

v5 工具调用变更

破坏性变更:

  • parameters → inputSchema(Zod schema)
  • 工具属性:args → input,result → output
  • 移除 ToolExecutionError(现在使用 tool-error 内容部分)
  • 移除 maxSteps 参数 → 使用 stopWhen(stepCountIs(n))

v5 新增功能:

  • 动态工具(根据上下文在运行时添加工具)
  • Agent 类(使用工具进行多步执行)

关键的 v4→v5 迁移

AI SDK v5 引入了大量破坏性变更。如果要从 v4 迁移,请遵循本指南。

重大变更概览
  1. 参数重命名

    • maxTokens → maxOutputTokens
    • providerMetadata → providerOptions
  2. 工具定义

    • parameters → inputSchema
    • 工具属性:args → input,result → output
  3. 消息类型

    • CoreMessage → ModelMessage
    • Message → UIMessage
    • convertToCoreMessages → convertToModelMessages
  4. 工具错误处理

    • 移除了 ToolExecutionError 类
    • 现在使用 tool-error 内容部分
    • 支持自动重试
  5. 多步执行

    • maxSteps → stopWhen
    • 使用 stepCountIs() 或 hasToolCall()
  6. 消息结构

    • 简单的 content 字符串 → parts 数组
    • 部分类型:文本、文件、推理、工具调用、工具结果
  7. 流式架构

    • 单个数据块 → start/delta/end 生命周期
    • 为并发流使用唯一 ID
  8. 工具流式传输

    • 默认启用
    • 移除了 toolCallStreaming 选项
  9. 包重组

    • ai/rsc → @ai-sdk/rsc
    • ai/react → @ai-sdk/react
    • LangChainAdapter → @ai-sdk/langchain
迁移示例

迁移前(v4):

import { generateText } from 'ai';

const result = await generateText({
  model: openai.chat('gpt-4-turbo'),
  maxTokens: 500,
  providerMetadata: { openai: { user: 'user-123' } },
  tools: {
    weather: {
      description: 'Get weather',
      parameters: z.object({ location: z.string() }),
      execute: async (args) => { /* args.location */ },
    },
  },
  maxSteps: 5,
});

迁移后(v5):

import { generateText, tool, stopWhen, stepCountIs } from 'ai';

const result = await generateText({
  model: openai('gpt-4-turbo'),
  maxOutputTokens: 500,
  providerOptions: { openai: { user: 'user-123' } },
  tools: {
    weather: tool({
      description: 'Get weather',
      inputSchema: z.object({ location: z.string() }),
      execute: async ({ location }) => { /* input.location */ },
    }),
  },
  stopWhen: stepCountIs(5),
});
迁移检查清单
  • 将所有 maxTokens 更新为 maxOutputTokens
  • 将 providerMetadata 更新为 providerOptions
  • 将工具的 parameters 转换为 inputSchema
  • 更新工具执行函数:args → input
  • 将 maxSteps 替换为 stopWhen(stepCountIs(n))
  • 更新消息类型:CoreMessage → ModelMessage
  • 移除 ToolExecutionError 处理
  • 更新包导入(ai/rsc → @ai-sdk/rsc)
  • 测试流式行为(架构已变更)
  • 更新 TypeScript 类型
自动迁移

AI SDK 提供了迁移工具:

npx ai migrate

这会自动更新大多数重大变更。请仔细检查变更。

官方迁移指南: https://ai-sdk.dev/docs/migration-guides/migration-guide-5-0


15 大错误及解决方案

1. AI_APICallError

原因: API 请求失败(网络、身份验证、速率限制)。

解决方案:

import { AI_APICallError } from 'ai';

try {
  const result = await generateText({
    model: openai('gpt-4-turbo'),
    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
    }
  }
}

预防措施:

  • 启动时验证 API 密钥
  • 使用指数退避实现重试逻辑
  • 监控速率限制
  • 妥善处理网络错误

2. AI_NoObjectGeneratedError

原因: 模型未生成符合架构的有效对象。

解决方案:

import { AI_NoObjectGeneratedError } from 'ai';

try {
  const result = await generateObject({
    model: openai('gpt-4-turbo'),
    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-5 or claude-sonnet-4-5 for complex objects)
  }
}

预防措施:

  • 从简单架构开始,逐步增加复杂度
  • 在提示词中包含示例:“生成类似这样的人员:{ name: 'Alice', age: 30 }”
  • 对于复杂的结构化输出,使用 GPT-4
  • 先用示例数据测试架构

3. Worker 启动限制(270ms+)

原因: Cloudflare Workers 中 AI SDK v5 和 Zod 的初始化开销超出启动限制。

解决方案:

// 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
  }
}

预防措施:

  • 将 AI SDK 导入移到路由处理函数内部
  • 尽量减少顶层 Zod 架构
  • 监控 Worker 启动时间(必须小于 400ms)
  • 使用 Wrangler 的启动时间报告

GitHub 问题: 在 Vercel AI SDK 问题中搜索“Workers startup limit”


4. streamText 静默失败

原因: createDataStreamResponse 可能会吞掉流错误。

状态: ✅ 已解决 - 已在 [email protected] 中修复(2025 年 2 月)

解决方案(推荐):

// Use the onError callback (added in v4.1.22)
const stream = streamText({
  model: openai('gpt-4-turbo'),
  prompt: 'Hello',
  onError({ error }) {
    console.error('Stream error:', error);
    // Custom error logging and handling
  },
});

// Stream safely
for await (const chunk of stream.textStream) {
  process.stdout.write(chunk);
}

替代方案(手动 try-catch):

// Fallback if not using onError callback
try {
  const stream = streamText({
    model: openai('gpt-4-turbo'),
    prompt: 'Hello',
  });

  for await (const chunk of stream.textStream) {
    process.stdout.write(chunk);
  }
} catch (error) {
  console.error('Stream error:', error);
}

预防措施:

  • 使用 onError 回调以正确捕获错误(推荐)
  • 实施服务端错误监控
  • 明确测试流错误处理
  • 在生产环境中始终在服务端记录日志

GitHub 问题: #4726(已解决)


5. AI_LoadAPIKeyError

原因: 缺少或 API 密钥无效。

解决方案:

import { AI_LoadAPIKeyError } from 'ai';

try {
  const result = await generateText({
    model: openai('gpt-4-turbo'),
    prompt: 'Hello',
  });
} catch (error) {
  if (error instanceof AI_LoadAPIKeyError) {
    console.error('API key error:', error.message);

    // Check:
    // 1. .env file exists and loaded
    // 2. Correct env variable name (OPENAI_API_KEY)
    // 3. Key format is valid (starts with sk-)
  }
}

预防措施:

  • 在应用启动时验证 API 密钥
  • 使用环境变量验证(例如 zod)
  • 在开发环境中提供清晰的错误消息
  • 记录必需的环境变量

6. AI_InvalidArgumentError

原因: 传递给函数的参数无效。

解决方案:

import { AI_InvalidArgumentError } from 'ai';

try {
  const result = await generateText({
    model: openai('gpt-4-turbo'),
    maxOutputTokens: -1,  // Invalid!
    prompt: 'Hello',
  });
} catch (error) {
  if (error instanceof AI_InvalidArgumentError) {
    console.error('Invalid argument:', error.message);
    // Check parameter types and values
  }
}

预防措施:

  • 使用 TypeScript 进行类型检查
  • 调用 AI SDK 函数前验证输入
  • 仔细阅读函数签名
  • 查看官方文档,了解参数限制

7. AI_NoContentGeneratedError

原因: 模型未生成任何内容(安全过滤器等)。

解决方案:

import { AI_NoContentGeneratedError } from 'ai';

try {
  const result = await generateText({
    model: openai('gpt-4-turbo'),
    prompt: 'Some prompt',
  });
} catch (error) {
  if (error instanceof AI_NoContentGeneratedError) {
    console.error('No content generated');

    // Possible causes:
    // 1. Safety filters blocked output
    // 2. Prompt triggered content policy
    // 3. Model configuration issue

    // Handle gracefully:
    return { text: 'Unable to generate response. Please try different input.' };
  }
}

预防措施:

  • 清理用户输入
  • 避免可能触发安全过滤器的提示词
  • 准备备用消息
  • 记录发生情况以供分析

8. AI_TypeValidationError

原因: 生成的输出未通过 Zod 架构验证。

解决方案:

import { AI_TypeValidationError } from 'ai';

try {
  const result = await generateObject({
    model: openai('gpt-4-turbo'),
    schema: z.object({
      age: z.number().min(0).max(120),  // Strict validation
    }),
    prompt: 'Generate person',
  });
} catch (error) {
  if (error instanceof AI_TypeValidationError) {
    console.error('Validation failed:', error.message);

    // Solutions:
    // 1. Relax schema constraints
    // 2. Add more guidance in prompt
    // 3. Use .optional() for unreliable fields
  }
}

预防措施:

  • 从宽松的架构开始,逐步收紧
  • 对可能并非始终存在的字段使用 .optional()
  • 在字段描述中添加验证提示
  • 使用各种提示词进行测试

9. AI_RetryError

原因: 所有重试均失败。

解决方案:

import { AI_RetryError } from 'ai';

try {
  const result = await generateText({
    model: openai('gpt-4-turbo'),
    prompt: 'Hello',
    maxRetries: 3,  // Default is 2
  });
} catch (error) {
  if (error instanceof AI_RetryError) {
    console.error('All retries failed');
    console.error('Last error:', error.lastError);

    // Check root cause:
    // - Persistent network issue
    // - Provider outage
    // - Invalid configuration
  }
}

预防措施:

  • 调查失败的根本原因
  • 根据需要调整重试配置
  • 在提供商中断时实施熔断器模式
  • 准备备用提供商

10. 速率限制错误

原因: 超出提供商的速率限制(RPM/TPM)。

解决方案:

// Implement exponential backoff
async function generateWithBackoff(prompt: string, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      return await generateText({
        model: openai('gpt-4-turbo'),
        prompt,
      });
    } catch (error) {
      if (error instanceof AI_APICallError && error.statusCode === 429) {
        const delay = Math.pow(2, i) * 1000;  // Exponential backoff
        console.log(`Rate limited, waiting ${delay}ms`);
        await new Promise(resolve => setTimeout(resolve, delay));
      } else {
        throw error;
      }
    }
  }
  throw new Error('Rate limit retries exhausted');
}

预防措施:

  • 监控速率限制标头
  • 对请求进行排队,以确保不超出限制
  • 根据需要升级提供商套餐
  • 实施请求限流

11. 使用 Zod 时的 TypeScript 性能问题

原因: 复杂的 Zod 架构会拖慢 TypeScript 类型检查。

解决方案:

// Instead of deeply nested schemas at top level:
// const complexSchema = z.object({ /* 100+ fields */ });

// Define inside functions or use type assertions:
function generateData() {
  const schema = z.object({ /* complex schema */ });
  return generateObject({ model: openai('gpt-4-turbo'), schema, prompt: '...' });
}

// Or use z.lazy() for recursive schemas:
type Category = { name: string; subcategories?: Category[] };
const CategorySchema: z.ZodType<Category> = z.lazy(() =>
  z.object({
    name: z.string(),
    subcategories: z.array(CategorySchema).optional(),
  })
);

预防措施:

  • 避免使用顶层复杂架构
  • 对递归类型使用 z.lazy()
  • 将大型架构拆分为较小的架构
  • 在适当情况下使用类型断言

官方文档: https://ai-sdk.dev/docs/troubleshooting/common-issues/slow-type-checking


12. 无效 JSON 响应(特定提供商)

原因: 某些模型偶尔会返回无效 JSON。

解决方案:

// Use built-in retry and mode selection
const result = await generateObject({
  model: openai('gpt-4-turbo'),
  schema: mySchema,
  prompt: 'Generate data',
  mode: 'json',  // Force JSON mode (supported by GPT-4)
  maxRetries: 3,  // Retry on invalid JSON
});

// Or catch and retry manually:
try {
  const result = await generateObject({
    model: openai('gpt-4-turbo'),
    schema: mySchema,
    prompt: 'Generate data',
  });
} catch (error) {
  // Retry with different model
  const result = await generateObject({
    model: openai('gpt-4-turbo'),
    schema: mySchema,
    prompt: 'Generate data',
  });
}

预防措施:

  • 在可用时使用 mode: 'json'
  • 对结构化输出优先使用 GPT-4
  • 实施重试逻辑
  • 验证响应

GitHub Issue: #4302(Imagen 3.0 无效 JSON)


13. Gemini 隐式缓存因工具而失效

错误:没有错误,但由于缓存被禁用,API 费用更高 原因:只要定义了任何工具,Google Gemini 3 Flash 的节省成本型隐式缓存就无法工作,即使这些工具从未被使用。 来源:GitHub Issue #11513

发生原因:请求中存在工具时,Gemini API 会禁用缓存,无论这些工具是否被调用。

预防措施:

// Conditionally add tools only when needed
const needsTools = await analyzePrompt(userInput);

const result = await generateText({
  model: google('gemini-3-flash'),
  tools: needsTools ? { weather: weatherTool } : undefined,
  prompt: userInput,
});

影响:高——重复使用上下文时,API 费用可能大幅增加


14. Anthropic 工具错误结果导致 JSON 解析崩溃

错误:SyntaxError: "[object Object]" is not valid JSON 原因:Anthropic 提供商的内置工具(web_fetch 等)会返回错误对象,而 SDK 会尝试对其进行 JSON.parse 来源:GitHub Issue #11856

发生原因:Anthropic 内置工具失败时(例如 url_not_allowed),会返回错误对象。AI SDK 错误地尝试将这些对象解析为 JSON 字符串。

预防措施:

try {
  const result = await generateText({
    model: anthropic('claude-sonnet-4-5-20250929'),
    tools: { web_fetch: { type: 'anthropic_defined', name: 'web_fetch' } },
    prompt: userPrompt,
  });
} catch (error) {
  if (error.message.includes('is not valid JSON')) {
    // Tool returned error result, handle gracefully
    console.error('Tool execution failed - likely blocked URL or permission issue');
    // Retry without tool or use custom tool
  }
  throw error;
}

影响:高——使用 Anthropic 内置工具时,生产环境可能崩溃


15. 助手消息中的工具结果(Anthropic)

错误:Anthropic API 错误 - 不允许在助手消息中使用 tool-result 原因:服务端执行的工具错误地将 tool-result 部分放在助手消息中 来源:GitHub Issue #11855

发生原因:使用服务端执行的工具(即 execute 在服务端运行,而不是发送给模型的工具)时,AI SDK 会错误地将 tool-result 部分包含在助手消息中。Anthropic 要求 tool-result 只能出现在用户消息中。

预防措施:

// Workaround: Filter messages before sending
const filteredMessages = messages.map(msg => {
  if (msg.role === 'assistant') {
    return {
      ...msg,
      content: msg.content.filter(part => part.type !== 'tool-result'),
    };
  }
  return msg;
});

const result = await generateText({
  model: anthropic('claude-sonnet-4-5-20250929'),
  tools: { database: databaseTool },
  messages: filteredMessages,
  prompt: 'Get user data',
});

影响:高 - 导致 Anthropic 提供方的服务端执行工具模式无法使用

状态:已知问题,已提交 PR #11854


更多错误: https://ai-sdk.dev/docs/reference/ai-sdk-errors(共 31 个)


已知问题和限制

useChat 在使用记忆化选项时出现过时闭包

问题:将 useChat 与记忆化选项搭配使用时(这在性能优化中很常见),onData 和 onFinish 回调会持有过时闭包,无法获取已更新的状态变量。

来源:GitHub Issue #11686

复现:

const [count, setCount] = useState(0);

const chatOptions = useMemo(() => ({
  onFinish: (message) => {
    console.log('Count:', count); // ALWAYS 0, never updates!
  },
}), []); // Empty deps = stale closure

const { messages, append } = useChat(chatOptions);

解决方法 1 - 不要记忆化回调:

const { messages, append } = useChat({
  onFinish: (message) => {
    console.log('Count:', count); // Now sees current count
  },
});

解决方法 2 - 使用 useRef:

const countRef = useRef(count);
useEffect(() => { countRef.current = count; }, [count]);

const chatOptions = useMemo(() => ({
  onFinish: (message) => {
    console.log('Count:', countRef.current); // Always current
  },
}), []);

完整复现示例: https://github.com/alechoey/ai-sdk-stale-ondata-repro


切换标签页时流恢复失败

问题:用户在 AI 流式传输期间切换浏览器标签页或将应用置于后台时,返回后流不会恢复。连接会断开,也不会自动重新连接。

来源:GitHub Issue #11865

影响:高 - 长时间运行的流存在严重的用户体验问题

解决方法 1 - 实现 onError 处理程序:

const { messages, append, reload } = useChat({
  api: '/api/chat',
  onError: (error) => {
    if (error.message.includes('stream') || error.message.includes('aborted')) {
      // Attempt to reload last message
      reload();
    }
  },
});

解决方法 2 - 检测可见性变化:

useEffect(() => {
  const handleVisibilityChange = () => {
    if (document.visibilityState === 'visible') {
      // Check if stream was interrupted
      const lastMessage = messages[messages.length - 1];
      if (lastMessage?.role === 'assistant' && !lastMessage.content) {
        reload();
      }
    }
  };

  document.addEventListener('visibilitychange', handleVisibilityChange);
  return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
}, [messages, reload]);

状态:已知限制,不内置自动重连功能


何时使用此技能

以下情况使用 ai-sdk-core:
  • 构建后端 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
  • 需要在不同大模型提供方之间使用一致的 API
以下情况不要使用此技能:
  • 构建 React 聊天界面(请改用 ai-sdk-ui 技能)
  • 需要 useChat 等前端钩子(请改用 ai-sdk-ui 技能)
  • 需要嵌入或图像生成等高级主题(请查看官方文档)
  • 构建不涉及多提供方的原生 Cloudflare Workers AI 应用(请改用 cloudflare-workers-ai 技能)
  • 需要 Generative UI / RSC(请参阅 https://ai-sdk.dev/docs/ai-sdk-rsc)

版本

AI SDK:

  • 稳定版:[email protected](2026 年 1 月)
  • ⚠️ 跳过 v6.0.40 - 流式传输变更会造成破坏性影响(已在 v6.0.41 中回退)
  • 旧版 v5:[email protected](ai-v5 标签)
  • 同时支持 Zod 3.x/4.x

最新模型(2026):

  • OpenAI:GPT-5.2、GPT-5.1、GPT-5、o3、o3-mini、o4-mini
  • Anthropic:Claude Sonnet 4.5、Opus 4.1、Haiku 4.5
  • Google:Gemini 2.5 Pro/Flash/Lite

查看最新版本:

npm view ai version
npm view ai dist-tags

官方文档

核心:

多模态:

GitHub:


最后更新: 2026-01-20 技能版本: 2.1.0 变更: 新增 3 个错误(Gemini 缓存、Anthropic 工具错误、工具结果位置)、MCP 安全指南、工具审批最佳实践、React Hooks 边缘情况、流恢复解决方法 AI SDK: 6.0.26 稳定版(避免使用 v6.0.40)

评论

支持 Markdown