Vercel AI SDK — Build AI-Powered Apps in TypeScript
You are an expert in the Vercel AI SDK, the TypeScript toolkit for building AI-powered applications. You help developers integrate LLMs (OpenAI, Anthropic, Google, Mistral, Ollama) with React Server Components, streaming UI, tool calling, structured output with Zod schemas, RAG pipelines, multi-step agents, and edge-compatible AI features — the standard way to add AI to Next.js, Nuxt, SvelteKit, and any Node.js app.
Core Capabilities
Core AI Functions
// AI SDK Core — works in any Node.js/Edge environment
import { generateText, generateObject, streamText, streamObject, tool } from "ai";
import { openai } from "@ai-sdk/openai";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";
// Simple text generation
const { text } = await generateText({
model: openai("gpt-4o"),
prompt: "Explain quantum computing in 3 sentences",
});
// Structured output with Zod schema
const { object: analysis } = await generateObject({
model: anthropic("claude-sonnet-4-20250514"),
schema: z.object({
sentiment: z.enum(["positive", "negative", "neutral"]),
topics: z.array(z.string()),
summary: z.string(),
confidence: z.number().min(0).max(1),
}),
prompt: `Analyze this review: "${reviewText}"`,
});
// analysis.sentiment → "positive" (fully typed)
// Streaming text
const result = streamText({
model: openai("gpt-4o"),
messages: [{ role: "user", content: "Write a poem about TypeScript" }],
});
for await (const chunk of result.textStream) {
process.stdout.write(chunk);
}
// Tool calling (agents)
const { text: answer, toolResults } = await generateText({
model: openai("gpt-4o"),
tools: {
getWeather: tool({
description: "Get weather for a city",
parameters: z.object({ city: z.string() }),
execute: async ({ city }) => {
const res = await fetch(`https://wttr.in/${city}?format=j1`);
return res.json();
},
}),
searchDatabase: tool({
description: "Search products database",
parameters: z.object({ query: z.string(), limit: z.number().default(5) }),
execute: async ({ query, limit }) => db.products.search(query, limit),
}),
},
maxSteps: 5, // Multi-step agent loop
prompt: "What's the weather in Tokyo and find related travel products?",
});
React / Next.js Integration
// app/api/chat/route.ts — API route with streaming
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai("gpt-4o"),
system: "You are a helpful assistant.",
messages,
});
return result.toDataStreamResponse();
}
// app/chat/page.tsx — Client component
"use client";
import { useChat } from "ai/react";
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();
return (
<div>
{messages.map(m => (
<div key={m.id} className={m.role === "user" ? "text-right" : "text-left"}>
<p>{m.content}</p>
</div>
))}
<form
<input value={input} placeholder="Ask anything..." />
<button type="submit" disabled={isLoading}>Send</button>
</form>
</div>
);
}
// Streaming UI with RSC
import { streamUI } from "ai/rsc";
async function submitMessage(input: string) {
"use server";
const result = await streamUI({
model: openai("gpt-4o"),
messages: [{ role: "user", content: input }],
tools: {
showStockPrice: {
description: "Show stock price chart",
parameters: z.object({ symbol: z.string() }),
generate: async function* ({ symbol }) {
yield <Spinner />;
const data = await getStockData(symbol);
return <StockChart data={data} />; // Stream React components!
},
},
},
});
return result.value;
}
Provider Switching
import { openai } from "@ai-sdk/openai";
import { anthropic } from "@ai-sdk/anthropic";
import { google } from "@ai-sdk/google";
import { createOllama } from "ollama-ai-provider";
const ollama = createOllama({ baseURL: "http://localhost:11434/api" });
// Same code, different providers
const models = {
fast: openai("gpt-4o-mini"),
smart: anthropic("claude-sonnet-4-20250514"),
vision: google("gemini-2.0-flash"),
local: ollama("llama3"),
};
const { text } = await generateText({
model: models[selectedModel], // Switch provider with zero code changes
prompt: userQuery,
});
Installation
npm install ai @ai-sdk/openai @ai-sdk/anthropic
# Provider packages: @ai-sdk/google, @ai-sdk/mistral, ollama-ai-provider
Best Practices
- generateObject for structured data — Use Zod schemas for type-safe AI output; no manual JSON parsing
- streamText for UX — Always stream responses to users; time-to-first-token matters more than total time
- Tool calling for agents — Define tools with Zod parameters; AI SDK handles the tool call loop automatically
- maxSteps for multi-step — Set
maxSteps: 5-10 for agent loops; AI calls tools, gets results, reasons, repeats
- Provider abstraction — Use AI SDK providers to swap models without changing app code; test with cheap models, deploy with smart ones
- useChat hook — Use in React for chat UIs; handles streaming, message history, loading state, error handling
- Edge-compatible — AI SDK works on Vercel Edge, Cloudflare Workers, Deno; stream from the edge for lower latency
- Telemetry — Enable
experimental_telemetry for OpenTelemetry traces; track token usage, latency, errors
1---2name: ai-sdk3description: >-4 You are an expert in the Vercel AI SDK, the TypeScript toolkit for building5 AI-powered applications. You help developers integrate LLMs (OpenAI,6 Anthropic, Google, Mistral, Ollama) with React Server Components, streaming7 UI, tool calling, structured output with Zod schemas, RAG pipelines,8 multi-step agents, and edge-compatible AI features — the standard way to add9 AI to Next.js, Nuxt, SvelteKit, and any Node.js app.10license: Apache-2.011compatibility: ''12metadata:13 source: https://skillmd.com/skills/eliferjunior/ai-sdk14 author: terminal-skills15 version: 1.0.016 category: AI & Machine Learning17 tags:18 - vercel19 - ai20 - llm21 - streaming22 - react23 - typescript24 - openai25 - anthropic26---2728# Vercel AI SDK — Build AI-Powered Apps in TypeScript2930You are an expert in the Vercel AI SDK, the TypeScript toolkit for building AI-powered applications. You help developers integrate LLMs (OpenAI, Anthropic, Google, Mistral, Ollama) with React Server Components, streaming UI, tool calling, structured output with Zod schemas, RAG pipelines, multi-step agents, and edge-compatible AI features — the standard way to add AI to Next.js, Nuxt, SvelteKit, and any Node.js app.3132## Core Capabilities3334### Core AI Functions3536```typescript37// AI SDK Core — works in any Node.js/Edge environment38import { generateText, generateObject, streamText, streamObject, tool } from "ai";39import { openai } from "@ai-sdk/openai";40import { anthropic } from "@ai-sdk/anthropic";41import { z } from "zod";4243// Simple text generation44const { text } = await generateText({45 model: openai("gpt-4o"),46 prompt: "Explain quantum computing in 3 sentences",47});4849// Structured output with Zod schema50const { object: analysis } = await generateObject({51 model: anthropic("claude-sonnet-4-20250514"),52 schema: z.object({53 sentiment: z.enum(["positive", "negative", "neutral"]),54 topics: z.array(z.string()),55 summary: z.string(),56 confidence: z.number().min(0).max(1),57 }),58 prompt: `Analyze this review: "${reviewText}"`,59});60// analysis.sentiment → "positive" (fully typed)6162// Streaming text63const result = streamText({64 model: openai("gpt-4o"),65 messages: [{ role: "user", content: "Write a poem about TypeScript" }],66});67for await (const chunk of result.textStream) {68 process.stdout.write(chunk);69}7071// Tool calling (agents)72const { text: answer, toolResults } = await generateText({73 model: openai("gpt-4o"),74 tools: {75 getWeather: tool({76 description: "Get weather for a city",77 parameters: z.object({ city: z.string() }),78 execute: async ({ city }) => {79 const res = await fetch(`https://wttr.in/${city}?format=j1`);80 return res.json();81 },82 }),83 searchDatabase: tool({84 description: "Search products database",85 parameters: z.object({ query: z.string(), limit: z.number().default(5) }),86 execute: async ({ query, limit }) => db.products.search(query, limit),87 }),88 },89 maxSteps: 5, // Multi-step agent loop90 prompt: "What's the weather in Tokyo and find related travel products?",91});92```9394### React / Next.js Integration9596```tsx97// app/api/chat/route.ts — API route with streaming98import { streamText } from "ai";99import { openai } from "@ai-sdk/openai";100101export async function POST(req: Request) {102 const { messages } = await req.json();103104 const result = streamText({105 model: openai("gpt-4o"),106 system: "You are a helpful assistant.",107 messages,108 });109110 return result.toDataStreamResponse();111}112113// app/chat/page.tsx — Client component114"use client";115import { useChat } from "ai/react";116117export default function Chat() {118 const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();119120 return (121 <div>122 {messages.map(m => (123 <div key={m.id} className={m.role === "user" ? "text-right" : "text-left"}>124 <p>{m.content}</p>125 </div>126 ))}127 <form onSubmit={handleSubmit}>128 <input value={input} onChange={handleInputChange} placeholder="Ask anything..." />129 <button type="submit" disabled={isLoading}>Send</button>130 </form>131 </div>132 );133}134135// Streaming UI with RSC136import { streamUI } from "ai/rsc";137138async function submitMessage(input: string) {139 "use server";140 const result = await streamUI({141 model: openai("gpt-4o"),142 messages: [{ role: "user", content: input }],143 tools: {144 showStockPrice: {145 description: "Show stock price chart",146 parameters: z.object({ symbol: z.string() }),147 generate: async function* ({ symbol }) {148 yield <Spinner />;149 const data = await getStockData(symbol);150 return <StockChart data={data} />; // Stream React components!151 },152 },153 },154 });155 return result.value;156}157```158159### Provider Switching160161```typescript162import { openai } from "@ai-sdk/openai";163import { anthropic } from "@ai-sdk/anthropic";164import { google } from "@ai-sdk/google";165import { createOllama } from "ollama-ai-provider";166167const ollama = createOllama({ baseURL: "http://localhost:11434/api" });168169// Same code, different providers170const models = {171 fast: openai("gpt-4o-mini"),172 smart: anthropic("claude-sonnet-4-20250514"),173 vision: google("gemini-2.0-flash"),174 local: ollama("llama3"),175};176177const { text } = await generateText({178 model: models[selectedModel], // Switch provider with zero code changes179 prompt: userQuery,180});181```182183## Installation184185```bash186npm install ai @ai-sdk/openai @ai-sdk/anthropic187# Provider packages: @ai-sdk/google, @ai-sdk/mistral, ollama-ai-provider188```189190## Best Practices1911921. **generateObject for structured data** — Use Zod schemas for type-safe AI output; no manual JSON parsing1932. **streamText for UX** — Always stream responses to users; time-to-first-token matters more than total time1943. **Tool calling for agents** — Define tools with Zod parameters; AI SDK handles the tool call loop automatically1954. **maxSteps for multi-step** — Set `maxSteps: 5-10` for agent loops; AI calls tools, gets results, reasons, repeats1965. **Provider abstraction** — Use AI SDK providers to swap models without changing app code; test with cheap models, deploy with smart ones1976. **useChat hook** — Use in React for chat UIs; handles streaming, message history, loading state, error handling1987. **Edge-compatible** — AI SDK works on Vercel Edge, Cloudflare Workers, Deno; stream from the edge for lower latency1998. **Telemetry** — Enable `experimental_telemetry` for OpenTelemetry traces; track token usage, latency, errors