ai-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vercel AI SDK v6 Patterns

Vercel AI SDK v6 模式

Zod 4.x

Zod 4.x

This repo uses Zod 4.x (4.3.5+) directly:
typescript
// ✅ Standard Zod 4 import
import { z } from 'zod'
Zod 4's optimized types work well with AI SDK v6's recursive generics.

Comprehensive guide for Vercel AI SDK v6 (6.0+) patterns used in agent-first applications. Contains rules for provider setup, tool definitions, multi-step workflows, and result extraction.
本仓库直接使用 Zod 4.x(4.3.5+):
typescript
// ✅ 标准 Zod 4 导入
import { z } from 'zod'
Zod 4 优化后的类型与 AI SDK v6 的递归泛型适配性良好。

本指南全面介绍了面向Agent优先应用的Vercel AI SDK v6(6.0+)模式,包含模型提供商设置规则、工具定义、多步骤工作流及结果提取方法。

When to Apply

适用场景

Reference these guidelines when:
  • Setting up AI model providers
  • Defining agent tools with tool()
  • Implementing multi-step agentic workflows
  • Extracting results from generateText/streamText
  • Migrating from AI SDK v5 to v6
在以下场景中可参考本指南:
  • 配置AI模型提供商
  • 使用tool()定义Agent工具
  • 实现多步骤Agent工作流
  • 从generateText/streamText中提取结果
  • 从AI SDK v5迁移至v6

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Provider SetupCRITICAL
provider-
2Text GenerationHIGH
generate-
3Tool DefinitionsHIGH
tool-
4Multi-Step AgentsHIGH
agent-
5Result ExtractionMEDIUM
result-
6Message TypesMEDIUM
message-
7Error HandlingMEDIUM
error-
优先级类别影响程度前缀
1提供商设置关键
provider-
2文本生成
generate-
3工具定义
tool-
4多步骤Agent
agent-
5结果提取
result-
6消息类型
message-
7错误处理
error-

Quick Reference

快速参考

Critical v6 Breaking Changes

v6 重大破坏性变更

typescript
// ❌ v5 patterns that FAIL in v6:
import { type CoreMessage } from 'ai'     // → ModelMessage
parameters: z.object({...})               // → inputSchema
maxSteps: 5                               // → stopWhen: stepCountIs(5)
call.args                                 // → call.input
call.toolResult                           // → step.toolResults[].output
typescript
// ❌ 在v6中失效的v5模式:
import { type CoreMessage } from 'ai'     // → 替换为ModelMessage
parameters: z.object({...})               // → 替换为inputSchema
maxSteps: 5                               // → 替换为stopWhen: stepCountIs(5)
call.args                                 // → 替换为call.input
call.toolResult                           // → 替换为step.toolResults[].output

1. Provider Setup (CRITICAL)

1. 提供商设置(关键)

  • provider-gateway
    - Use AI Gateway model strings (recommended)
typescript
import { generateText } from 'ai'

const result = await generateText({
  model: 'anthropic/claude-opus-4-5',  // AI Gateway string
  prompt: 'Hello',
})
No provider wrapper is required when using AI Gateway model strings.
  • provider-gateway
    - 使用AI Gateway模型字符串(推荐)
typescript
import { generateText } from 'ai'

const result = await generateText({
  model: 'anthropic/claude-opus-4-5',  // AI Gateway字符串
  prompt: 'Hello',
})
使用AI Gateway模型字符串时无需提供商包装器

2. Text Generation (HIGH)

2. 文本生成(高)

  • generate-basic
    - Core generateText pattern
  • generate-basic
    - 核心generateText模式

3. Tool Definitions (HIGH)

3. 工具定义(高)

  • tool-input-schema
    - v6 uses inputSchema not parameters
  • tool-definition
    - Complete tool() pattern
typescript
import { tool } from 'ai'
import { z } from 'zod'

const myTool = tool({
  description: 'What this does',
  inputSchema: z.object({  // ✅ inputSchema not parameters
    param: z.string().describe('Description'),
  }),
  execute: async ({ param }) => {
    return { result: 'done' }
  },
})
  • tool-input-schema
    - v6使用inputSchema而非parameters
  • tool-definition
    - 完整的tool()模式
typescript
import { tool } from 'ai'
import { z } from 'zod'

const myTool = tool({
  description: '工具功能说明',
  inputSchema: z.object({  // ✅ 使用inputSchema而非parameters
    param: z.string().describe('参数描述'),
  }),
  execute: async ({ param }) => {
    return { result: '完成' }
  },
})

4. Multi-Step Agents (HIGH)

4. 多步骤Agent(高)

  • agent-stop-when
    - v6 uses stopWhen not maxSteps
  • agent-multi-step
    - Complete agent pattern
typescript
import { generateText, stepCountIs } from 'ai'

const result = await generateText({
  model: 'anthropic/claude-opus-4-5',
  messages,
  tools: agentTools,
  stopWhen: stepCountIs(5),  // ✅ not maxSteps: 5
})
  • agent-stop-when
    - v6使用stopWhen而非maxSteps
  • agent-multi-step
    - 完整的Agent模式
typescript
import { generateText, stepCountIs } from 'ai'

const result = await generateText({
  model: 'anthropic/claude-opus-4-5',
  messages,
  tools: agentTools,
  stopWhen: stepCountIs(5),  // ✅ 而非maxSteps: 5
})

5. Result Extraction (MEDIUM)

5. 结果提取(中)

  • result-tool-access
    - Access tool calls and results correctly
typescript
// ✅ Correct v6 pattern
const toolCalls = result.steps.flatMap((step) => {
  const resultsMap = new Map(
    (step.toolResults || []).map((r) => [r.toolCallId, r.output])
  )
  return (step.toolCalls || []).map((tc) => ({
    name: tc.toolName,
    args: tc.input,  // ✅ input not args
    result: resultsMap.get(tc.toolCallId),  // ✅ from toolResults
  }))
})
  • result-tool-access
    - 正确访问工具调用及结果
typescript
// ✅ v6正确模式
const toolCalls = result.steps.flatMap((step) => {
  const resultsMap = new Map(
    (step.toolResults || []).map((r) => [r.toolCallId, r.output])
  )
  return (step.toolCalls || []).map((tc) => ({
    name: tc.toolName,
    args: tc.input,  // ✅ 使用input而非args
    result: resultsMap.get(tc.toolCallId),  // ✅ 从toolResults获取
  }))
})

6. Message Types (MEDIUM)

6. 消息类型(中)

  • message-model-message
    - Use ModelMessage type
typescript
import { type ModelMessage } from 'ai'  // ✅ not CoreMessage

const messages: ModelMessage[] = [
  { role: 'user', content: 'Hello' },
]
  • message-model-message
    - 使用ModelMessage类型
typescript
import { type ModelMessage } from 'ai'  // ✅ 而非CoreMessage

const messages: ModelMessage[] = [
  { role: 'user', content: '你好' },
]

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/provider-gateway.md
rules/tool-input-schema.md
rules/agent-stop-when.md
rules/result-tool-access.md
rules/_sections.md
Each rule file contains:
  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Reference links
阅读单个规则文件以获取详细说明及代码示例:
rules/provider-gateway.md
rules/tool-input-schema.md
rules/agent-stop-when.md
rules/result-tool-access.md
rules/_sections.md
每个规则文件包含:
  • 规则重要性简述
  • 错误代码示例及说明
  • 正确代码示例及说明
  • 参考链接

Key Imports

核心导入

typescript
import {
  generateText,
  generateObject,
  streamText,
  streamObject,
  tool,
  stepCountIs,
  hasToolCall,
  type ModelMessage,
} from 'ai'
import { z } from 'zod'  // Zod 4.x
typescript
import {
  generateText,
  generateObject,
  streamText,
  streamObject,
  tool,
  stepCountIs,
  hasToolCall,
  type ModelMessage,
} from 'ai'
import { z } from 'zod'  // Zod 4.x

Model Strings (AI Gateway)

模型字符串(AI Gateway)

anthropic/claude-opus-4-5
anthropic/claude-sonnet-4
openai/gpt-4o
google/gemini-2.0-flash
Auth: Set
AI_GATEWAY_API_KEY
environment variable.
anthropic/claude-opus-4-5
anthropic/claude-sonnet-4
openai/gpt-4o
google/gemini-2.0-flash
认证:设置
AI_GATEWAY_API_KEY
环境变量。