Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

refactor(ai-sdk-core): Knowledge-gap audit - Add AI SDK 6 beta, latest models (GPT-5, Claude 4)

Jez44336e024f94
diff --git a/skills/ai-sdk-core/SKILL.md b/skills/ai-sdk-core/SKILL.md
index 16e17b60..ade2f515 100644
--- a/skills/ai-sdk-core/SKILL.md
+++ b/skills/ai-sdk-core/SKILL.md
@@ -1,22 +1,29 @@
---
name: ai-sdk-core
description: |
- Build backend AI features with Vercel AI SDK v5: text generation, structured output (Zod schemas),
- tool calling, and agents. Multi-provider support (OpenAI, Anthropic, Google, Cloudflare).
+ Build backend AI with Vercel AI SDK v5/v6. Covers v6 beta (Agent abstraction, tool approval, reranking),
+ v4→v5 migration (breaking changes), latest models (GPT-5/5.1, Claude 4.x, Gemini 2.5), Workers startup
+ fix, and 12 error solutions (AI_APICallError, AI_NoObjectGeneratedError, streamText silent errors).
- Use when: implementing server-side AI, generating text/structured data, building AI agents, streaming
- responses, or troubleshooting AI_APICallError, AI_NoObjectGeneratedError.
+ Use when: implementing AI SDK v5/v6, migrating v4→v5, troubleshooting errors, fixing Workers startup
+ issues, or updating to latest models.
license: MIT
metadata:
- version: 1.1.1
- last_verified: 2025-11-19
- ai_sdk_version: 5.0.95+
- breaking_changes: false
+ version: 1.2.0
+ last_verified: 2025-11-22
+ ai_sdk_version: 5.0.98 stable / 6.0.0-beta.107
+ breaking_changes: true (v4→v5 migration guide included)
production_tested: true
keywords:
- ai sdk core
- vercel ai sdk
- ai sdk v5
+ - ai sdk v6 beta
+ - ai sdk 6
+ - agent abstraction
+ - tool approval
+ - reranking support
+ - human in the loop
- generateText
- streamText
- generateObject
@@ -32,6 +39,12 @@ metadata:
- google gemini sdk
- cloudflare workers ai
- workers-ai-provider
+ - gpt-5
+ - gpt-5.1
+ - claude 4
+ - claude sonnet 4.5
+ - claude opus 4.1
+ - gemini 2.5
- ai streaming backend
- multi-provider ai
- ai provider abstraction
@@ -45,719 +58,143 @@ metadata:
# AI SDK Core
-Production-ready backend AI with Vercel AI SDK v5.
-
-## Quick Start (5 Minutes)
-
-### Installation
-
-```bash
-# Core package
-npm install ai
-
-# Provider packages (install what you need)
-npm install @ai-sdk/openai # OpenAI (GPT-5, GPT-4, GPT-3.5)
-npm install @ai-sdk/anthropic # Anthropic (Claude Sonnet 4.5, Opus 4, Haiku 4)
-npm install @ai-sdk/google # Google (Gemini 2.5 Pro/Flash/Lite)
-npm install workers-ai-provider # Cloudflare Workers AI
-
-# Schema validation
-npm install zod
-```
-
-### Environment Variables
+Backend AI with Vercel AI SDK v5 and v6 Beta.
+**Installation:**
```bash
-# .env
-OPENAI_API_KEY=sk-...
-ANTHROPIC_API_KEY=sk-ant-...
-GOOGLE_GENERATIVE_AI_API_KEY=...
-```
-
-### First 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);
-```
-
-### 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);
-}
-```
-
-### 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"] }
+npm install ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google zod
+# Beta: npm install ai@beta @ai-sdk/openai@beta
```
---
-## Core Functions
-
-### generateText()
-
-Generate text completion with optional tools and multi-step execution.
-
-**Signature:**
+## AI SDK 6 Beta (November 2025)
-```typescript
-async function generateText(options: {
- model: LanguageModel;
- prompt?: string;
- messages?: Array<ModelMessage>;
- system?: string;
- tools?: Record<string, Tool>;
- maxOutputTokens?: number;
- temperature?: number;
- stopWhen?: StopCondition;
- // ... other options
-}): Promise<GenerateTextResult>
-```
+**Status:** Beta (stable release planned end of 2025)
+**Latest:** [email protected] (Nov 22, 2025)
-**Basic Usage:**
+### New Features
-```typescript
-import { generateText } from 'ai';
-import { openai } from '@ai-sdk/openai';
+**1. Agent Abstraction**
+Unified interface for building agents with `ToolLoopAgent` class:
+- Full control over execution flow, tool loops, and state management
+- Replaces manual tool calling orchestration
-const result = await generateText({
- model: openai('gpt-4-turbo'),
- prompt: 'Explain quantum computing',
- maxOutputTokens: 500,
- temperature: 0.7,
-});
+**2. Tool Execution Approval (Human-in-the-Loop)**
+Request user confirmation before executing tools:
+- Static approval: Always ask for specific tools
+- Dynamic approval: Conditional based on tool inputs
+- Native human-in-the-loop pattern
-console.log(result.text);
-console.log(`Tokens: ${result.usage.totalTokens}`);
-```
+**3. Reranking Support**
+Improve search relevance by reordering documents:
+- Supported providers: Cohere, Amazon Bedrock, Together.ai
+- Specialized reranking models for RAG workflows
-**With Messages (Chat Format):**
+**4. Structured Output (Stable)**
+Combine multi-step tool calling with structured data generation:
+- Multiple output strategies: objects, arrays, choices, text formats
+- Now stable and production-ready in v6
-```typescript
-const result = await generateText({
- model: openai('gpt-4-turbo'),
- messages: [
- { role: 'system', content: 'You are a helpful assistant.' },
- { role: 'user', content: 'What is the weather?' },
- { role: 'assistant', content: 'I need your location.' },
- { role: 'user', content: 'San Francisco' },
- ],
-});
-```
+**5. Call Options**
+Dynamic runtime configuration:
+- Type-safe parameter passing
+- RAG integration, model selection, tool customization
+- Provider-specific settings adjustments
-**With Tools:**
+**6. Image Editing (Coming Soon)**
+Native support for image transformation workflows.
-```typescript
-import { tool } from 'ai';
-import { z } from 'zod';
+### Migration from v5
-const result = await generateText({
- model: openai('gpt-4'),
- tools: {
- weather: tool({
- description: 'Get the weather for a location',
- inputSchema: z.object({
- location: z.string(),
- }),
- execute: async ({ location }) => {
- // API call here
- return { temperature: 72, condition: 'sunny' };
- },
- }),
- },
- prompt: 'What is the weather in Tokyo?',
-});
-```
-
-**When to Use:**
-- Need final response (not streaming)
-- Want to wait for tool executions to complete
-- Simpler code when streaming not needed
-- Building batch/scheduled tasks
-
-**Error Handling:**
-
-```typescript
-import { AI_APICallError, AI_NoContentGeneratedError } from 'ai';
-
-try {
- const result = await generateText({
- model: openai('gpt-4-turbo'),
- prompt: 'Hello',
- });
- console.log(result.text);
-} catch (error) {
- if (error instanceof AI_APICallError) {
- console.error('API call failed:', error.message);
- // Check rate limits, API key, network
- } else if (error instanceof AI_NoContentGeneratedError) {
- console.error('No content generated');
- // Prompt may have been filtered
- } else {
- console.error('Unknown error:', error);
- }
-}
-```
-
----
-
-### streamText()
-
-Stream text completion with real-time chunks.
-
-**Signature:**
-
-```typescript
-function streamText(options: {
- model: LanguageModel;
- prompt?: string;
- messages?: Array<ModelMessage>;
- system?: string;
- tools?: Record<string, Tool>;
- maxOutputTokens?: number;
- temperature?: number;
- stopWhen?: StopCondition;
- // ... other options
-}): StreamTextResult
-```
-
-**Basic Streaming:**
-
-```typescript
-import { streamText } from 'ai';
-import { anthropic } from '@ai-sdk/anthropic';
-
-const stream = streamText({
- model: anthropic('claude-sonnet-4-5-20250929'),
- prompt: 'Write a poem about AI',
-});
-
-// Stream to console
-for await (const chunk of stream.textStream) {
- process.stdout.write(chunk);
-}
-
-// Or get final result
-const finalResult = await stream.result;
-console.log(finalResult.text);
-```
-
-**Streaming with Tools:**
-
-```typescript
-const stream = streamText({
- model: openai('gpt-4'),
- tools: {
- // ... tools definition
- },
- prompt: 'What is the weather?',
-});
-
-// Stream text chunks
-for await (const chunk of stream.textStream) {
- process.stdout.write(chunk);
-}
-```
-
-**Handling the Stream:**
-
-```typescript
-const stream = streamText({
- model: openai('gpt-4-turbo'),
- prompt: 'Explain AI',
-});
-
-// Option 1: Text stream
-for await (const text of stream.textStream) {
- console.log(text);
-}
-
-// Option 2: Full stream (includes metadata)
-for await (const part of stream.fullStream) {
- if (part.type === 'text-delta') {
- console.log(part.textDelta);
- } else if (part.type === 'tool-call') {
- console.log('Tool called:', part.toolName);
- }
-}
+**Unlike v4→v5, v6 has minimal breaking changes:**
+- Powered by v3 Language Model Specification
+- Most users require no code changes
+- Agent abstraction is additive (opt-in)
-// Option 3: Wait for final result
-const result = await stream.result;
-console.log(result.text, result.usage);
-```
-
-**When to Use:**
-- Real-time user-facing responses
-- Long-form content generation
-- Want to show progress
-- Better perceived performance
-
-**Production Pattern:**
-
-```typescript
-// Next.js API Route
-import { streamText } from 'ai';
-import { openai } from '@ai-sdk/openai';
-
-export async function POST(request: Request) {
- const { messages } = await request.json();
-
- const stream = streamText({
- model: openai('gpt-4-turbo'),
- messages,
- });
-
- // Return stream to client
- return stream.toDataStreamResponse();
-}
-```
-
-**Error Handling:**
-
-```typescript
-// Recommended: Use 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 handling
- },
-});
-
-for await (const chunk of stream.textStream) {
- process.stdout.write(chunk);
-}
-
-// Alternative: Manual try-catch
-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);
-}
-```
-
----
-
-### generateObject()
-
-Generate structured output validated by Zod schema.
-
-**Signature:**
-
-```typescript
-async function generateObject<T>(options: {
- model: LanguageModel;
- schema: z.Schema<T>;
- prompt?: string;
- messages?: Array<ModelMessage>;
- system?: string;
- mode?: 'auto' | 'json' | 'tool';
- // ... other options
-}): Promise<GenerateObjectResult<T>>
-```
-
-**Basic Usage:**
-
-```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({
- recipe: z.object({
- name: z.string(),
- ingredients: z.array(z.object({
- name: z.string(),
- amount: z.string(),
- })),
- instructions: z.array(z.string()),
- }),
- }),
- prompt: 'Generate a recipe for chocolate chip cookies',
-});
-
-console.log(result.object.recipe);
-```
-
-**Nested Schemas:**
-
-```typescript
-const PersonSchema = z.object({
- name: z.string(),
- age: z.number(),
- address: z.object({
- street: z.string(),
- city: z.string(),
- country: z.string(),
- }),
- hobbies: z.array(z.string()),
-});
-
-const result = await generateObject({
- model: openai('gpt-4'),
- schema: PersonSchema,
- prompt: 'Generate a person profile',
-});
-```
-
-**Arrays and Unions:**
-
-```typescript
-// Array of objects
-const result = await generateObject({
- model: openai('gpt-4'),
- schema: z.object({
- people: z.array(z.object({
- name: z.string(),
- role: z.enum(['engineer', 'designer', 'manager']),
- })),
- }),
- prompt: 'Generate a team of 5 people',
-});
-
-// Union types
-const result = await generateObject({
- model: openai('gpt-4'),
- schema: z.discriminatedUnion('type', [
- z.object({ type: z.literal('text'), content: z.string() }),
- z.object({ type: z.literal('image'), url: z.string() }),
- ]),
- prompt: 'Generate content',
-});
-```
-
-**When to Use:**
-- Need structured data (JSON, forms, etc.)
-- Validation is critical
-- Extracting data from unstructured input
-- Building AI workflows that consume JSON
-
-**Error Handling:**
-
-```typescript
-import { AI_NoObjectGeneratedError, AI_TypeValidationError } from 'ai';
-
-try {
- const result = await generateObject({
- model: openai('gpt-4'),
- schema: z.object({ name: z.string() }),
- prompt: 'Generate a person',
- });
-} catch (error) {
- if (error instanceof AI_NoObjectGeneratedError) {
- console.error('Model did not generate valid object');
- // Try simplifying schema or adding examples
- } else if (error instanceof AI_TypeValidationError) {
- console.error('Zod validation failed:', error.message);
- // Schema doesn't match output
- }
-}
-```
-
----
-
-### streamObject()
-
-Stream structured output with partial updates.
-
-**Signature:**
-
-```typescript
-function streamObject<T>(options: {
- model: LanguageModel;
- schema: z.Schema<T>;
- prompt?: string;
- messages?: Array<ModelMessage>;
- mode?: 'auto' | 'json' | 'tool';
- // ... other options
-}): StreamObjectResult<T>
-```
-
-**Basic Usage:**
-
-```typescript
-import { streamObject } from 'ai';
-import { google } from '@ai-sdk/google';
-import { z } from 'zod';
-
-const stream = streamObject({
- model: google('gemini-2.5-pro'),
- schema: z.object({
- characters: z.array(z.object({
- name: z.string(),
- class: z.string(),
- stats: z.object({
- hp: z.number(),
- mana: z.number(),
- }),
- })),
- }),
- prompt: 'Generate 3 RPG characters',
-});
-
-// Stream partial updates
-for await (const partialObject of stream.partialObjectStream) {
- console.log(partialObject);
- // { characters: [{ name: "Aria" }] }
- // { characters: [{ name: "Aria", class: "Mage" }] }
- // { characters: [{ name: "Aria", class: "Mage", stats: { hp: 100 } }] }
- // ...
-}
-```
-
-**UI Integration Pattern:**
-
-```typescript
-// Server endpoint
-export async function POST(request: Request) {
- const { prompt } = await request.json();
-
- const stream = streamObject({
- model: openai('gpt-4'),
- schema: z.object({
- summary: z.string(),
- keyPoints: z.array(z.string()),
- }),
- prompt,
- });
-
- return stream.toTextStreamResponse();
-}
-
-// Client (with useObject hook from ai-sdk-ui)
-const { object, isLoading } = useObject({
- api: '/api/analyze',
- schema: /* same schema */,
-});
-
-// Render partial object as it streams
-{object?.summary && <p>{object.summary}</p>}
-{object?.keyPoints?.map(point => <li key={point}>{point}</li>)}
+**Install Beta:**
+```bash
+npm install ai@beta @ai-sdk/openai@beta @ai-sdk/react@beta
```
-**When to Use:**
-- Real-time structured data (forms, dashboards)
-- Show progressive completion
-- Large structured outputs
-- Better UX for slow generations
+**Official Docs:** https://ai-sdk.dev/docs/announcing-ai-sdk-6-beta
---
-## Provider Setup & Configuration
+## Latest AI Models (2025)
### OpenAI
-```typescript
-import { openai } from '@ai-sdk/openai';
-import { generateText } from 'ai';
-
-// API key from environment (recommended)
-// OPENAI_API_KEY=sk-...
-const model = openai('gpt-4-turbo');
-
-// Or explicit API key
-const model = openai('gpt-4', {
- apiKey: process.env.OPENAI_API_KEY,
-});
-
-// Available models
-const gpt5 = openai('gpt-5'); // Latest (released August 2025)
-const gpt4 = openai('gpt-4-turbo');
-const gpt35 = openai('gpt-3.5-turbo');
-
-const result = await generateText({
- model: gpt4,
- prompt: 'Hello',
-});
-```
-
-**Common Errors:**
-- `AI_LoadAPIKeyError`: Check `OPENAI_API_KEY` environment variable
-- `429 Rate Limit`: Implement exponential backoff, upgrade tier
-- `401 Unauthorized`: Invalid API key format
+**GPT-5** (Aug 7, 2025):
+- 45% less hallucination than GPT-4o
+- State-of-the-art in math, coding, visual perception, health
+- Available in ChatGPT, API, GitHub Models, Microsoft Copilot
-**Rate Limiting:**
-OpenAI enforces RPM (requests per minute) and TPM (tokens per minute) limits. Implement retry logic:
+**GPT-5.1** (Nov 13, 2025):
+- Improved speed and efficiency over GPT-5
+- Available in API platform
```typescript
-const result = await generateText({
- model: openai('gpt-4'),
- prompt: 'Hello',
- maxRetries: 3, // Built-in retry
-});
+import { openai } from '@ai-sdk/openai';
+const gpt5 = openai('gpt-5');
+const gpt51 = openai('gpt-5.1');
```
----
-
### Anthropic
+**Claude 4 Family** (May-Oct 2025):
+- **Opus 4** (May 22): Best for complex reasoning, $15/$75 per million tokens
+- **Sonnet 4** (May 22): Balanced performance, $3/$15 per million tokens
+- **Opus 4.1** (Aug 5): Enhanced agentic tasks, real-world coding
+- **Sonnet 4.5** (Sept 29): Most capable for coding, agents, computer use
+- **Haiku 4.5** (Oct 15): Small, fast, low-latency model
+
```typescript
import { anthropic } from '@ai-sdk/anthropic';
-
-// ANTHROPIC_API_KEY=sk-ant-...
-const claude = anthropic('claude-sonnet-4-5-20250929');
-
-// Available models (Claude 4.x family, released 2025)
-const sonnet45 = anthropic('claude-sonnet-4-5-20250929'); // Latest, recommended
-const sonnet4 = anthropic('claude-sonnet-4-20250522'); // Released May 2025
-const opus4 = anthropic('claude-opus-4-20250522'); // Highest quality
-
-// Legacy models (Claude 3.x, deprecated)
-// const sonnet35 = anthropic('claude-3-5-sonnet-20241022'); // Use Claude 4.x instead
-// const opus3 = anthropic('claude-3-opus-20240229');
-// const haiku3 = anthropic('claude-3-haiku-20240307');
-
-const result = await generateText({
- model: sonnet45,
- prompt: 'Explain quantum entanglement',
-});
+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');
```
-**Common Errors:**
-- `AI_LoadAPIKeyError`: Check `ANTHROPIC_API_KEY` environment variable
-- `overloaded_error`: Retry with exponential backoff
-- `rate_limit_error`: Wait and retry
-
-**Best Practices:**
-- Claude excels at long-context tasks (200K+ tokens)
-- **Claude 4.x recommended**: Anthropic deprecated Claude 3.x in 2025
-- Use Sonnet 4.5 for balance of speed/quality (latest model)
-- Use Sonnet 4 for production stability (if avoiding latest)
-- Use Opus 4 for highest quality reasoning and complex tasks
-
----
-
### Google
+**Gemini 2.5 Family** (Mar-Sept 2025):
+- **Pro** (March 2025): Most intelligent, #1 on LMArena at launch
+- **Pro Deep Think** (May 2025): Enhanced reasoning mode
+- **Flash** (May 2025): Fast, cost-effective
+- **Flash-Lite** (Sept 2025): Updated efficiency
+
```typescript
import { google } from '@ai-sdk/google';
-
-// GOOGLE_GENERATIVE_AI_API_KEY=...
-const gemini = google('gemini-2.5-pro');
-
-// Available models (all GA since June-July 2025)
const pro = google('gemini-2.5-pro');
const flash = google('gemini-2.5-flash');
const lite = google('gemini-2.5-flash-lite');
-
-const result = await generateText({
- model: pro,
- prompt: 'Analyze this data',
-});
```
-**Common Errors:**
-- `AI_LoadAPIKeyError`: Check `GOOGLE_GENERATIVE_AI_API_KEY`
-- `SAFETY`: Content filtered by safety settings
-- `QUOTA_EXCEEDED`: Rate limit hit
-
-**Best Practices:**
-- Gemini Pro: Best for reasoning and analysis
-- Gemini Flash: Fast, cost-effective for most tasks
-- Free tier has generous limits
-- Good for multimodal tasks (combine with image inputs)
-
---
-### Cloudflare Workers AI
-
-```typescript
-import { Hono } from 'hono';
-import { generateText } from 'ai';
-import { createWorkersAI } from 'workers-ai-provider';
-
-interface Env {
- AI: Ai;
-}
-
-const app = new Hono<{ Bindings: Env }>();
-
-app.post('/chat', async (c) => {
- // Create provider inside handler (avoid startup overhead)
- const workersai = createWorkersAI({ binding: c.env.AI });
-
- const result = await generateText({
- model: workersai('@cf/meta/llama-3.1-8b-instruct'),
- prompt: 'What is Cloudflare?',
- });
-
- return c.json({ response: result.text });
-});
+## v5 Core Functions (Basics)
-export default app;
-```
+**generateText()** - Text completion with tools
+**streamText()** - Real-time streaming
+**generateObject()** - Structured output (Zod schemas)
+**streamObject()** - Streaming structured data
-**wrangler.jsonc:**
+See official docs for usage: https://ai-sdk.dev/docs/ai-sdk-core
-```jsonc
-{
- "name": "ai-sdk-worker",
- "compatibility_date": "2025-10-21",
- "ai": {
- "binding": "AI"
- }
-}
-```
+---
-**Important Notes:**
+## Cloudflare Workers Startup Fix
-**Startup Optimization:**
-AI SDK v5 + Zod can cause >270ms startup time in Workers. Solutions:
+**Problem:** AI SDK v5 + Zod causes >270ms startup time (exceeds Workers 400ms limit).
-1. **Move imports inside handler:**
+**Solution:**
```typescript
-// BAD (startup overhead)
+// ❌ BAD: Top-level imports cause startup overhead
import { createWorkersAI } from 'workers-ai-provider';
const workersai = createWorkersAI({ binding: env.AI });
-// GOOD (lazy init)
+// ✅ GOOD: Lazy initialization inside handler
app.post('/chat', async (c) => {
const { createWorkersAI } = await import('workers-ai-provider');
const workersai = createWorkersAI({ binding: c.env.AI });
@@ -765,189 +202,24 @@ app.post('/chat', async (c) => {
});
```
-2. **Minimize top-level Zod schemas:**
-```typescript
-// Move complex schemas into route handlers
-```
-
-**When to Use workers-ai-provider:**
-- Multi-provider scenarios (OpenAI + Workers AI)
-- Using AI SDK UI hooks with Workers AI
-- Need consistent API across providers
-
-**When to Use Native Binding:**
-For Cloudflare-only deployments without multi-provider support, use the `cloudflare-workers-ai` skill instead for maximum performance.
+**Additional:**
+- Minimize top-level Zod schemas
+- Move complex schemas into route handlers
+- Monitor startup time with Wrangler
---
-## Tool Calling & Agents
+## v5 Tool Calling Changes
-### Basic Tool Definition
-
-```typescript
-import { generateText, tool } from 'ai';
-import { openai } from '@ai-sdk/openai';
-import { z } from 'zod';
-
-const result = await generateText({
- model: openai('gpt-4'),
- tools: {
- weather: tool({
- description: 'Get the weather for a location',
- inputSchema: z.object({
- location: z.string().describe('The city and country, e.g. "Paris, France"'),
- unit: z.enum(['celsius', 'fahrenheit']).optional(),
- }),
- execute: async ({ location, unit = 'celsius' }) => {
- // Simulate API call
- const data = await fetch(`https://api.weather.com/${location}`);
- return { temperature: 72, condition: 'sunny', unit };
- },
- }),
- convertTemperature: tool({
- description: 'Convert temperature between units',
- inputSchema: z.object({
- value: z.number(),
- from: z.enum(['celsius', 'fahrenheit']),
- to: z.enum(['celsius', 'fahrenheit']),
- }),
- execute: async ({ value, from, to }) => {
- if (from === to) return { value };
- if (from === 'celsius' && to === 'fahrenheit') {
- return { value: (value * 9/5) + 32 };
- }
- return { value: (value - 32) * 5/9 };
- },
- }),
- },
- prompt: 'What is the weather in Tokyo in Fahrenheit?',
-});
-
-console.log(result.text);
-// Model will call weather tool, potentially convertTemperature, then answer
-```
-
-**v5 Tool Changes:**
+**Breaking Changes:**
- `parameters` → `inputSchema` (Zod schema)
- Tool properties: `args` → `input`, `result` → `output`
- `ToolExecutionError` removed (now `tool-error` content parts)
+- `maxSteps` parameter removed → Use `stopWhen(stepCountIs(n))`
----
-
-### Agent Class
-
-The Agent class simplifies multi-step execution with tools.
-
-```typescript
-import { Agent, tool } from 'ai';
-import { anthropic } from '@ai-sdk/anthropic';
-import { z } from 'zod';
-
-const weatherAgent = new Agent({
- model: anthropic('claude-sonnet-4-5-20250929'),
- system: 'You are a weather assistant. Always convert temperatures to the user\'s preferred unit.',
- tools: {
- getWeather: tool({
- description: 'Get current weather for a location',
- inputSchema: z.object({
- location: z.string(),
- }),
- execute: async ({ location }) => {
- return { temp: 72, condition: 'sunny', unit: 'fahrenheit' };
- },
- }),
- convertTemp: tool({
- description: 'Convert temperature between units',
- inputSchema: z.object({
- fahrenheit: z.number(),
- }),
- execute: async ({ fahrenheit }) => {
- return { celsius: (fahrenheit - 32) * 5/9 };
- },
- }),
- },
-});
-
-const result = await weatherAgent.run({
- messages: [
- { role: 'user', content: 'What is the weather in SF in Celsius?' },
- ],
-});
-
-console.log(result.text);
-// Agent will call getWeather, then convertTemp, then respond
-```
-
-**When to Use Agent vs Raw generateText:**
-- **Use Agent when:** Multiple tools, complex workflows, multi-step reasoning
-- **Use generateText when:** Simple single-step, one or two tools, full control needed
-
----
-
-### Multi-Step Execution
-
-Control when multi-step execution stops with `stopWhen` conditions.
-
-```typescript
-import { generateText, stopWhen, stepCountIs, hasToolCall } from 'ai';
-import { openai } from '@ai-sdk/openai';
-
-// Stop after specific number of steps
-const result = await generateText({
- model: openai('gpt-4'),
- tools: { /* ... */ },
- prompt: 'Research TypeScript and create a summary',
- stopWhen: stepCountIs(5), // Max 5 steps (tool calls + responses)
-});
-
-// Stop when specific tool is called
-const result = await generateText({
- model: openai('gpt-4'),
- tools: {
- research: tool({ /* ... */ }),
- finalize: tool({ /* ... */ }),
- },
- prompt: 'Research and finalize a report',
- stopWhen: hasToolCall('finalize'), // Stop when finalize is called
-});
-
-// Combine conditions
-const result = await generateText({
- model: openai('gpt-4'),
- tools: { /* ... */ },
- prompt: 'Complex task',
- stopWhen: (step) => step.stepCount >= 10 || step.hasToolCall('finish'),
-});
-```
-
-**v5 Change:**
-`maxSteps` parameter removed. Use `stopWhen(stepCountIs(n))` instead.
-
----
-
-### Dynamic Tools (v5 New Feature)
-
-Add tools at runtime based on context:
-
-```typescript
-const result = await generateText({
- model: openai('gpt-4'),
- tools: (context) => {
- // Context includes messages, step count, etc.
- const baseTool = {
- search: tool({ /* ... */ }),
- };
-
- // Add tools based on context
- if (context.messages.some(m => m.content.includes('weather'))) {
- baseTool.weather = tool({ /* ... */ });
- }
-
- return baseTools;
- },
- prompt: 'Help me with my task',
-});
-```
+**New in v5:**
+- Dynamic tools (add tools at runtime based on context)
+- Agent class (multi-step execution with tools)
---
@@ -1508,201 +780,7 @@ try {
---
-**For More Errors:**
-See complete error reference at https://ai-sdk.dev/docs/reference/ai-sdk-errors
-
----
-
-## Production Best Practices
-
-### Performance
-
-**1. Always use streaming for long-form content:**
-```typescript
-// User-facing: Use streamText
-const stream = streamText({ model: openai('gpt-4'), prompt: 'Long essay' });
-return stream.toDataStreamResponse();
-
-// Background tasks: Use generateText
-const result = await generateText({ model: openai('gpt-4'), prompt: 'Analyze data' });
-```
-
-**2. Set appropriate maxOutputTokens:**
-```typescript
-const result = await generateText({
- model: openai('gpt-4'),
- prompt: 'Short answer',
- maxOutputTokens: 100, // Limit tokens to save cost
-});
-```
-
-**3. Cache provider instances:**
-```typescript
-// Good: Reuse provider instances
-const gpt4 = openai('gpt-4-turbo');
-const result1 = await generateText({ model: gpt4, prompt: 'Hello' });
-const result2 = await generateText({ model: gpt4, prompt: 'World' });
-```
-
-**4. Optimize Zod schemas:**
-```typescript
-// Avoid complex nested schemas at top level in Workers
-// Move into route handlers to prevent startup overhead
-```
-
-### Error Handling
-
-**1. Wrap all AI calls in try-catch:**
-```typescript
-try {
- const result = await generateText({ /* ... */ });
-} catch (error) {
- // Handle specific errors
- if (error instanceof AI_APICallError) { /* ... */ }
- else if (error instanceof AI_NoContentGeneratedError) { /* ... */ }
- else { /* ... */ }
-}
-```
-
-**2. Implement retry logic:**
-```typescript
-const result = await generateText({
- model: openai('gpt-4'),
- prompt: 'Hello',
- maxRetries: 3,
-});
-```
-
-**3. Log errors properly:**
-```typescript
-console.error('AI SDK Error:', {
- type: error.constructor.name,
- message: error.message,
- statusCode: error.statusCode,
- timestamp: new Date().toISOString(),
-});
-```
-
-### Cost Optimization
-
-**1. Choose appropriate models:**
-```typescript
-// Simple tasks: Use cheaper models
-const simple = await generateText({ model: openai('gpt-3.5-turbo'), prompt: 'Hello' });
-
-// Complex reasoning: Use GPT-4
-const complex = await generateText({ model: openai('gpt-4'), prompt: 'Analyze...' });
-```
-
-**2. Set maxOutputTokens appropriately:**
-```typescript
-const result = await generateText({
- model: openai('gpt-4'),
- prompt: 'Summarize in 2 sentences',
- maxOutputTokens: 100, // Prevent over-generation
-});
-```
-
-**3. Cache results when possible:**
-```typescript
-const cache = new Map();
-
-async function getCachedResponse(prompt: string) {
- if (cache.has(prompt)) return cache.get(prompt);
-
- const result = await generateText({ model: openai('gpt-4'), prompt });
- cache.set(prompt, result.text);
- return result.text;
-}
-```
-
-### Cloudflare Workers Specific
-
-**1. Move imports inside handlers:**
-```typescript
-// Avoid startup overhead
-export default {
- async fetch(request, env) {
- const { generateText } = await import('ai');
- const { openai } = await import('@ai-sdk/openai');
- // Use here
- }
-}
-```
-
-**2. Monitor startup time:**
-```bash
-# Wrangler reports startup time
-wrangler deploy
-# Check output for startup duration (must be <400ms)
-```
-
-**3. Handle streaming properly:**
-```typescript
-// Return ReadableStream for streaming responses
-const stream = streamText({ model: openai('gpt-4'), prompt: 'Hello' });
-return new Response(stream.toTextStream(), {
- headers: { 'Content-Type': 'text/plain; charset=utf-8' },
-});
-```
-
-### Next.js / Vercel Specific
-
-**1. Use Server Actions for mutations:**
-```typescript
-'use server';
-
-export async function generateContent(input: string) {
- const result = await generateText({
- model: openai('gpt-4'),
- prompt: input,
- });
- return result.text;
-}
-```
-
-**2. Use Server Components for initial loads:**
-```typescript
-// app/page.tsx
-export default async function Page() {
- const result = await generateText({
- model: openai('gpt-4'),
- prompt: 'Welcome message',
- });
-
- return <div>{result.text}</div>;
-}
-```
-
-**3. Implement loading states:**
-```typescript
-'use client';
-
-import { useState } from 'react';
-import { generateContent } from './actions';
-
-export default function Form() {
- const [loading, setLoading] = useState(false);
-
- async function handleSubmit(formData: FormData) {
- setLoading(true);
- const result = await generateContent(formData.get('input'));
- setLoading(false);
- }
-
- return (
- <form action={handleSubmit}>
- <input name="input" />
- <button disabled={loading}>
- {loading ? 'Generating...' : 'Submit'}
- </button>
- </form>
- );
-}
-```
-
-**4. For deployment:**
-See Vercel's official deployment documentation: https://vercel.com/docs/functions
+**More Errors:** https://ai-sdk.dev/docs/reference/ai-sdk-errors (28 total)
---
@@ -1731,119 +809,41 @@ See Vercel's official deployment documentation: https://vercel.com/docs/function
---
-## Dependencies & Versions
-
-```json
-{
- "dependencies": {
- "ai": "^5.0.95",
- "@ai-sdk/openai": "^2.0.68",
- "@ai-sdk/anthropic": "^2.0.45",
- "@ai-sdk/google": "^2.0.38",
- "workers-ai-provider": "^2.0.0",
- "zod": "^3.23.8"
- },
- "devDependencies": {
- "@types/node": "^20.11.0",
- "typescript": "^5.3.3"
- }
-}
-```
+## Versions
+
+**AI SDK:**
+- Stable: [email protected] (Nov 20, 2025)
+- Beta: [email protected] (Nov 22, 2025)
+- Zod 3.x/4.x both supported (3.23.8 recommended)
-**Version Notes:**
-- AI SDK v5.0.95+ (stable, latest as of November 2025)
-- v6 is in beta - not covered in this skill
-- **Zod compatibility**: This skill uses Zod 3.x for maximum compatibility, but AI SDK 5 officially supports both Zod 3.x and Zod 4.x (4.1.12 latest)
- - Zod 3.23.8 recommended for templates (stable, maximum compatibility)
- - Zod 4 has breaking changes: error APIs, `.default()` behavior, `ZodError.errors` removed
- - Some peer dependency warnings may occur with `zod-to-json-schema` when using Zod 4
- - See https://zod.dev/v4/changelog for migration guide
-- Provider packages at 2.0+ for v5 compatibility
-- **Model updates (Nov 2025)**: Latest models include GPT-5.1, GPT-4.1, o3 (OpenAI); Claude Sonnet 4.5, Opus 4.0, Haiku 4.5 (Anthropic)
-
-**Check Latest Versions:**
+**Latest Models (2025):**
+- OpenAI: GPT-5.1, GPT-5, o3
+- Anthropic: Claude Sonnet 4.5, Opus 4.1, Haiku 4.5
+- Google: Gemini 2.5 Pro/Flash/Lite
+
+**Check Latest:**
```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 updates
+npm view ai dist-tags # See beta versions
```
---
-## 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
-
-### 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
-
-### 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
-
-### Cloudflare Integration
-
-- **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/
-
-### Vercel / Next.js Integration
-
-- **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
-
-### GitHub & Community
-
-- **GitHub Repository:** https://github.com/vercel/ai
-- **GitHub Issues:** https://github.com/vercel/ai/issues
-- **Discord Community:** https://discord.gg/vercel
-
----
-
-## Templates & References
-
-This skill includes:
+## Official Docs
-- **13 Templates:** Ready-to-use code examples in `templates/`
-- **5 Reference Docs:** Detailed guides in `references/`
-- **1 Script:** Version checker in `scripts/`
+**Core:**
+- AI SDK 6 Beta: https://ai-sdk.dev/docs/announcing-ai-sdk-6-beta
+- AI SDK Core: https://ai-sdk.dev/docs/ai-sdk-core/overview
+- v4→v5 Migration: https://ai-sdk.dev/docs/migration-guides/migration-guide-5-0
+- All Errors (28): https://ai-sdk.dev/docs/reference/ai-sdk-errors
+- Providers (25+): https://ai-sdk.dev/providers/overview
-All files are optimized for copy-paste into your project.
+**GitHub:**
+- Repository: https://github.com/vercel/ai
+- Issues: https://github.com/vercel/ai/issues
---
-**Last Updated:** 2025-11-19
-**Skill Version:** 1.1.1
-**AI SDK Version:** 5.0.95+
+**Last Updated:** 2025-11-22
+**Skill Version:** 1.2.0
+**AI SDK:** 5.0.98 stable / 6.0.0-beta.107