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: 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.4license: Apache-2.05---67# Vercel AI SDK — Build AI-Powered Apps in TypeScript89You 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.1011## Core Capabilities1213### Core AI Functions1415```typescript16// AI SDK Core — works in any Node.js/Edge environment17import { generateText, generateObject, streamText, streamObject, tool } from "ai";18import { openai } from "@ai-sdk/openai";19import { anthropic } from "@ai-sdk/anthropic";20import { z } from "zod";2122// Simple text generation23const { text } = await generateText({24 model: openai("gpt-4o"),25 prompt: "Explain quantum computing in 3 sentences",26});2728// Structured output with Zod schema29const { object: analysis } = await generateObject({30 model: anthropic("claude-sonnet-4-20250514"),31 schema: z.object({32 sentiment: z.enum(["positive", "negative", "neutral"]),33 topics: z.array(z.string()),34 summary: z.string(),35 confidence: z.number().min(0).max(1),36 }),37 prompt: `Analyze this review: "${reviewText}"`,38});39// analysis.sentiment → "positive" (fully typed)4041// Streaming text42const result = streamText({43 model: openai("gpt-4o"),44 messages: [{ role: "user", content: "Write a poem about TypeScript" }],45});46for await (const chunk of result.textStream) {47 process.stdout.write(chunk);48}4950// Tool calling (agents)51const { text: answer, toolResults } = await generateText({52 model: openai("gpt-4o"),53 tools: {54 getWeather: tool({55 description: "Get weather for a city",56 parameters: z.object({ city: z.string() }),57 execute: async ({ city }) => {58 const res = await fetch(`https://wttr.in/${city}?format=j1`);59 return res.json();60 },61 }),62 searchDatabase: tool({63 description: "Search products database",64 parameters: z.object({ query: z.string(), limit: z.number().default(5) }),65 execute: async ({ query, limit }) => db.products.search(query, limit),66 }),67 },68 maxSteps: 5, // Multi-step agent loop69 prompt: "What's the weather in Tokyo and find related travel products?",70});71```7273### React / Next.js Integration7475```tsx76// app/api/chat/route.ts — API route with streaming77import { streamText } from "ai";78import { openai } from "@ai-sdk/openai";7980export async function POST(req: Request) {81 const { messages } = await req.json();8283 const result = streamText({84 model: openai("gpt-4o"),85 system: "You are a helpful assistant.",86 messages,87 });8889 return result.toDataStreamResponse();90}9192// app/chat/page.tsx — Client component93"use client";94import { useChat } from "ai/react";9596export default function Chat() {97 const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();9899 return (100 <div>101 {messages.map(m => (102 <div key={m.id} className={m.role === "user" ? "text-right" : "text-left"}>103 <p>{m.content}</p>104 </div>105 ))}106 <form onSubmit={handleSubmit}>107 <input value={input} onChange={handleInputChange} placeholder="Ask anything..." />108 <button type="submit" disabled={isLoading}>Send</button>109 </form>110 </div>111 );112}113114// Streaming UI with RSC115import { streamUI } from "ai/rsc";116117async function submitMessage(input: string) {118 "use server";119 const result = await streamUI({120 model: openai("gpt-4o"),121 messages: [{ role: "user", content: input }],122 tools: {123 showStockPrice: {124 description: "Show stock price chart",125 parameters: z.object({ symbol: z.string() }),126 generate: async function* ({ symbol }) {127 yield <Spinner />;128 const data = await getStockData(symbol);129 return <StockChart data={data} />; // Stream React components!130 },131 },132 },133 });134 return result.value;135}136```137138### Provider Switching139140```typescript141import { openai } from "@ai-sdk/openai";142import { anthropic } from "@ai-sdk/anthropic";143import { google } from "@ai-sdk/google";144import { createOllama } from "ollama-ai-provider";145146const ollama = createOllama({ baseURL: "http://localhost:11434/api" });147148// Same code, different providers149const models = {150 fast: openai("gpt-4o-mini"),151 smart: anthropic("claude-sonnet-4-20250514"),152 vision: google("gemini-2.0-flash"),153 local: ollama("llama3"),154};155156const { text } = await generateText({157 model: models[selectedModel], // Switch provider with zero code changes158 prompt: userQuery,159});160```161162## Installation163164```bash165npm install ai @ai-sdk/openai @ai-sdk/anthropic166# Provider packages: @ai-sdk/google, @ai-sdk/mistral, ollama-ai-provider167```168169## Best Practices1701711. **generateObject for structured data** — Use Zod schemas for type-safe AI output; no manual JSON parsing1722. **streamText for UX** — Always stream responses to users; time-to-first-token matters more than total time1733. **Tool calling for agents** — Define tools with Zod parameters; AI SDK handles the tool call loop automatically1744. **maxSteps for multi-step** — Set `maxSteps: 5-10` for agent loops; AI calls tools, gets results, reasons, repeats1755. **Provider abstraction** — Use AI SDK providers to swap models without changing app code; test with cheap models, deploy with smart ones1766. **useChat hook** — Use in React for chat UIs; handles streaming, message history, loading state, error handling1777. **Edge-compatible** — AI SDK works on Vercel Edge, Cloudflare Workers, Deno; stream from the edge for lower latency1788. **Telemetry** — Enable `experimental_telemetry` for OpenTelemetry traces; track token usage, latency, errors