ai-sdk-core
Vercel AI SDK v5 for backend AI (text generation, structured output, tools, agents). Multi-provider. Use for server-side AI or encountering AI_APICallError, AI_NoObjectGeneratedError, streaming failures.
What this skill does
# AI SDK Core
Production-ready backend AI with Vercel AI SDK v5.
**Last Updated**: 2025-11-21
## Table of Contents
1. [Quick Start](#quick-start-5-minutes)
2. [Core Functions](#core-functions)
3. [Provider Setup & Configuration](#provider-setup--configuration)
4. [Tool Calling & Agents](#tool-calling--agents)
5. [Critical v4→v5 Migration](#critical-v4v5-migration)
6. [Top 12 Errors & Solutions](#top-12-errors--solutions)
7. [Production Best Practices](#production-best-practices)
8. [When to Load References](#when-to-load-references)
9. [When to Use This Skill](#when-to-use-this-skill)
10. [Dependencies & Versions](#dependencies--versions)
11. [Links to Official Documentation](#links-to-official-documentation)
12. [Templates & References](#templates--references)
---
## Quick Start (5 Minutes)
### Installation
```bash
bun add ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google workers-ai-provider zod # preferred
# or: npm install ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google workers-ai-provider zod
```
### Environment Variables
```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"] }
```
## 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** — `npm config set ignore-scripts true` (or Bun: disabled by default)
- **Cooldown period** — Wait 7 days for new package versions to be vetted by the community
- **Audit before installing** — Run `socket package score npm <pkg>` or use `socket npm install <pkg>` to check packages
Load the `dependency-upgrade` skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement.
---
## Core Functions
**Load `references/core-functions.md` for complete API reference** of all 4 core functions.
### Quick Overview
AI SDK v5 provides 4 core functions:
| Function | Output | Streaming | Use Case |
|----------|--------|-----------|----------|
| `generateText()` | Text | No | Batch processing, simple completions |
| `streamText()` | Text | Yes | Chat UIs, long responses |
| `generateObject()` | Structured | No | Data extraction, JSON generation |
| `streamObject()` | Structured | Yes | Real-time forms, progressive UIs |
### 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 `references/core-functions.md` for:** Complete signatures, tool usage patterns, error handling, streaming examples, comparison table
---
## Provider Setup & Configuration
**Load `references/provider-setup.md` for complete setup instructions** for all providers.
### Quick Overview
AI SDK v5 supports 4 major providers:
| Provider | Environment Variable | Latest Models |
|----------|---------------------|---------------|
| OpenAI | `OPENAI_API_KEY` | GPT-5, GPT-4 Turbo |
| Anthropic | `ANTHROPIC_API_KEY` | Claude Sonnet 4.5, Opus 4 |
| Google | `GOOGLE_GENERATIVE_AI_API_KEY` | Gemini 2.5 Pro/Flash |
| Cloudflare | Workers AI binding | 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 `references/provider-setup.md` for:** Complete API configuration, rate limiting, error handling, Cloudflare Workers optimization, model selection guides
---
## Tool Calling & Agents
**Load `references/tools-and-agents.md` for complete tool and agent documentation**.
### Quick Overview
Tools allow models to call external functions. Agents manage multi-step workflows.
**v5 Tool Changes:**
- `parameters` → `inputSchema` (Zod schema)
- Tool properties: `args` → `input`, `result` → `output`
- `maxSteps` → `stopWhen(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 `references/tools-and-agents.md` for:** Agent class usage, multi-step execution, dynamic tools, stop conditions
---
## Critical v4→v5 Migration
**Load `references/v4-to-v5-migration.md` for complete migration guide**.
### Key Breaking Changes
AI SDK v5 has 9 major breaking changes:
- `maxTokens` → `maxOutputTokens`
- `parameters` → `inputSchema` (Zod)
- `maxSteps` → `stopWhen(stepCountIs(n))`
- `CoreMessage` → `ModelMessage`
- Package reorganization (`ai/rsc` → `@ai-sdk/rsc`)
### Automated Migration
```bash
bunx ai migrate # Auto-migrates most changes
```
**→ Load `references/v4-to-v5-migration.md` for:** Complete breaking changes list, migration examples, checklist, official migration guide link
---
## Top 12 Errors & Solutions
### 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
---
### 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 wiRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.