Vercel AI SDK: A Comprehensive Guide to Building AI-Powered Web Applications
Author: Ruby Abdullah, PT RUBYTHALIB DATA KONSULTA Date: November 7, 2026 Category: Tutorial Tags: Vercel AI SDK, Next.js, AI, TypeScript, LLMIntroduction
The Vercel AI SDK (the ai npm package) has become one of the most developer-friendly toolkits for integrating large language models (LLMs) into modern web applications. Rather than dealing with the idiosyncrasies of each AI provider's API directly, the Vercel AI SDK provides a unified, TypeScript-first abstraction layer that works seamlessly with OpenAI, Anthropic, Google Gemini, and many other providers.
Whether you are building a customer support chatbot, a code assistant, a document summarizer, or a full autonomous agent, the Vercel AI SDK gives you the primitives you need without the boilerplate. It is designed to work particularly well with Next.js and React, but it is not limited to those frameworks — it runs anywhere Node.js runs.
In this tutorial, we will walk through the core capabilities of the Vercel AI SDK from the ground up: generating text, streaming responses, producing structured outputs, calling external tools, building multi-step agents, and integrating Retrieval Augmented Generation (RAG). By the end, you will have a solid, practical understanding of how to ship AI-powered features in production.
The examples in this guide use TypeScript and Next.js (App Router). The same concepts apply if you are using a different Node.js framework such as Express or Hono.
Installation and Setup
Prerequisites
- Node.js 18 or later
- A Next.js 14+ project (App Router recommended)
- API keys for at least one AI provider (OpenAI, Anthropic, or Google)
Installing the Packages
The core package is ai. You also need at least one provider SDK:
npm install ai
Choose one or more providers:
npm install @ai-sdk/openai
npm install @ai-sdk/anthropic
npm install @ai-sdk/google
Environment Variables
Create a .env.local file at the root of your Next.js project:
OPENAIAPIKEY=sk-...
ANTHROPICAPIKEY=sk-ant-...
GOOGLEGENERATIVEAIAPIKEY=AIza...
Never commit these keys to version control. Add .env.local to your .gitignore.
Project Structure
A typical AI-powered Next.js project using the AI SDK looks like this:
my-app/
├── app/
│ ├── api/
│ │ ├── chat/
│ │ │ └── route.ts # Streaming chat endpoint
│ │ ├── generate/
│ │ │ └── route.ts # Text generation endpoint
│ │ └── tools/
│ │ └── route.ts # Tool-calling endpoint
│ ├── chat/
│ │ └── page.tsx # Chat UI using useChat hook
│ └── layout.tsx
├── lib/
│ └── ai.ts # Shared model configuration
└── .env.local
Shared Model Configuration
Create lib/ai.ts to centralize your model choices:
// lib/ai.ts
import { openai } from '@ai-sdk/openai';
import { anthropic } from '@ai-sdk/anthropic';
import { google } from '@ai-sdk/google';
// Pick your default model per provider
export const defaultOpenAI = openai('gpt-4o');
export const defaultAnthropic = anthropic('claude-3-5-sonnet-20241022');
export const defaultGoogle = google('gemini-1.5-pro');
// Use this throughout your app
export const defaultModel = defaultOpenAI;
Basic Usage: Text Generation and Streaming
generateText — One-Shot Generation
generateText is the simplest way to call an LLM. It waits for the full response before returning, making it suitable for tasks where you need the complete output before proceeding (summarization, classification, translation).
// app/api/generate/route.ts
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
export async function POST(req: Request) {
const { prompt } = await req.json();
const { text, usage, finishReason } = await generateText({
model: openai('gpt-4o'),
system: 'You are a helpful assistant that writes concise, professional responses.',
prompt,
maxTokens: 1024,
temperature: 0.7,
});
return Response.json({ text, usage, finishReason });
}
You can also use messages instead of prompt for multi-turn conversations:
const { text } = await generateText({
model: openai('gpt-4o'),
messages: [
{ role: 'system', content: 'You are a code review assistant.' },
{ role: 'user', content: 'Review this function: ...' },
{ role: 'assistant', content: 'The function looks good overall, but...' },
{ role: 'user', content: 'Can you give a specific example of the fix?' },
],
});
streamText — Streaming Responses
For chat interfaces and long-form generation, streaming is essential. It delivers tokens to the client as they are generated, making the app feel fast and responsive.
// app/api/chat/route.ts
import { streamText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: anthropic('claude-3-5-sonnet-20241022'),
system: 'You are a helpful assistant.',
messages,
maxTokens: 2048,
});
// toDataStreamResponse() returns an SSE stream compatible with the AI SDK UI hooks
return result.toDataStreamResponse();
}
The toDataStreamResponse() method produces a Server-Sent Events (SSE) response in the format that the AI SDK UI hooks (useChat, useCompletion) expect.
AI SDK UI: useChat Hook
The useChat hook connects your React component to the streaming endpoint above with almost no boilerplate:
// app/chat/page.tsx
'use client';
import { useChat } from 'ai/react';
export default function ChatPage() {
const { messages, input, handleInputChange, handleSubmit, isLoading, error } = useChat({
api: '/api/chat',
initialMessages: [],
onError: (err) => console.error('Chat error:', err),
});
return (
{messages.map((message) => (
key={message.id}
className={p-3 rounded-lg ${
message.role === 'user' ? 'bg-blue-100 ml-auto' : 'bg-gray-100'
}}
>
{message.role}
{message.content}
))}
{isLoading &&
Thinking...
}
{error &&
Error: {error.message}
}
);
}
useCompletion Hook
For single-turn, prompt-completion use cases (not multi-turn chat), useCompletion is a lighter alternative:
'use client';
import { useCompletion } from 'ai/react';
export default function CompletionPage() {
const { completion, complete, isLoading } = useCompletion({
api: '/api/completion',
});
return (
Generate Summary
{isLoading &&
Generating...
}
{completion &&
{completion}
}
);
}
Structured Output with Zod
One of the most powerful features of the AI SDK is generateObject, which forces the model to return data that conforms to a Zod schema. This eliminates the fragility of parsing free-form JSON from LLM responses.
Defining a Schema
import { z } from 'zod';
const ProductSchema = z.object({
name: z.string().describe('Product name'),
category: z.enum(['electronics', 'clothing', 'food', 'other']).describe('Product category'),
price: z.number().positive().describe('Price in USD'),
tags: z.array(z.string()).max(5).describe('Relevant tags'),
inStock: z.boolean().describe('Whether the product is currently in stock'),
description: z.string().max(200).describe('Short product description'),
});
type Product = z.infer;
Using generateObject
// app/api/extract-product/route.ts
import { generateObject } from 'ai';
import { google } from '@ai-sdk/google';
import { z } from 'zod';
const ProductSchema = z.object({
name: z.string(),
category: z.enum(['electronics', 'clothing', 'food', 'other']),
price: z.number().positive(),
tags: z.array(z.string()).max(5),
inStock: z.boolean(),
description: z.string().max(200),
});
export async function POST(req: Request) {
const { text } = await req.json();
const { object } = await generateObject({
model: google('gemini-1.5-pro'),
schema: ProductSchema,
prompt: Extract structured product information from the following text:\n\n${text},
});
// object is fully typed as z.infer
return Response.json(object);
}
Generating Arrays of Objects
import { generateObject } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const { object: articles } = await generateObject({
model: openai('gpt-4o'),
output: 'array',
schema: z.object({
title: z.string(),
summary: z.string(),
readingTimeMinutes: z.number().int().positive(),
}),
prompt: 'Generate 5 article ideas about machine learning for beginners.',
});
// articles is an array of { title, summary, readingTimeMinutes }
console.log(articles);
streamObject for Large Outputs
When the structured output is large, you can stream it as well:
import { streamObject } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const ReportSchema = z.object({
title: z.string(),
sections: z.array(z.object({
heading: z.string(),
content: z.string(),
})),
conclusion: z.string(),
});
const { partialObjectStream } = await streamObject({
model: openai('gpt-4o'),
schema: ReportSchema,
prompt: 'Write a report about the impact of AI on software development.',
});
for await (const partial of partialObjectStream) {
// Incrementally receive the object as it is generated
console.log(partial);
}
Tool Calling / Function Calling
Tool calling allows the LLM to invoke external functions — fetching live data, executing code, querying databases — and incorporate the results into its response. The AI SDK makes this straightforward with the tool helper.
Defining Tools
// lib/tools.ts
import { tool } from 'ai';
import { z } from 'zod';
export const getWeatherTool = tool({
description: 'Get the current weather for a given city.',
parameters: z.object({
city: z.string().describe('The city name, e.g. "Jakarta"'),
unit: z.enum(['celsius', 'fahrenheit']).default('celsius'),
}),
execute: async ({ city, unit }) => {
// In a real app, call a weather API here
const temp = unit === 'celsius' ? 28 : 82;
return {
city,
temperature: temp,
unit,
condition: 'Partly cloudy',
humidity: '75%',
};
},
});
export const searchDatabaseTool = tool({
description: 'Search the product database for items matching a query.',
parameters: z.object({
query: z.string().describe('Search keywords'),
limit: z.number().int().min(1).max(20).default(5),
}),
execute: async ({ query, limit }) => {
// Replace with your actual database query
const mockResults = Array.from({ length: limit }, (, i) => ({
id: prod-${i + 1},
name: ${query} Product ${i + 1},
price: Math.floor(Math.random() 1000) + 100,
}));
return { results: mockResults, total: mockResults.length };
},
});
Using Tools with generateText
// app/api/agent/route.ts
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { getWeatherTool, searchDatabaseTool } from '@/lib/tools';
export async function POST(req: Request) {
const { prompt } = await req.json();
const { text, toolCalls, toolResults } = await generateText({
model: openai('gpt-4o'),
tools: {
getWeather: getWeatherTool,
searchDatabase: searchDatabaseTool,
},
maxSteps: 5, // Allow up to 5 tool call rounds
system: 'You are a helpful assistant. Use the available tools to answer user questions accurately.',
prompt,
});
return Response.json({ text, toolCalls, toolResults });
}
Streaming with Tools
import { streamText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { getWeatherTool } from '@/lib/tools';
const result = await streamText({
model: anthropic('claude-3-5-sonnet-20241022'),
tools: { getWeather: getWeatherTool },
maxSteps: 3,
messages,
});
return result.toDataStreamResponse();
The useChat hook on the client side automatically handles tool call/result round trips when streaming.
Client-Side Tool Calling
You can also define tools that execute on the client side (useful for browser APIs like geolocation):
// In your React component
const { messages, handleSubmit } = useChat({
api: '/api/chat',
experimentalonToolCall: async (toolCall) => {
if (toolCall.tool.name === 'getUserLocation') {
return new Promise((resolve) => {
navigator.geolocation.getCurrentPosition((pos) => {
resolve({
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
});
});
});
}
},
});
Multi-Step Agents
An agent is a loop where the LLM decides what to do next, executes tools, observes results, and repeats until it reaches a final answer. The maxSteps parameter in generateText and streamText enables this automatically.
A Research Agent Example
// lib/research-agent.ts,import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { tool } from 'ai';
import { z } from 'zod';
const webSearchTool = tool({
description: 'Search the web for current information on a topic.',
parameters: z.object({
query: z.string().describe('The search query'),
}),
execute: async ({ query }) => {
// Integrate with a real search API (Brave, Tavily, Serper, etc.)
console.log(
Searching for: ${query});return {
results: [
{ title: 'Example Result', url: 'https://example.com', snippet: 'Relevant content...' },
],
};
},
});
const scrapePageTool = tool({
description: 'Fetch and extract text content from a webpage URL.',
parameters: z.object({
url: z.string().url().describe('The URL to scrape'),
}),
execute: async ({ url }) => {
// Integrate with a scraping service
console.log(
Scraping: ${url});return { content: 'Page content here...', wordCount: 500 };
},
});
export async function runResearchAgent(topic: string) {
const { text, steps } = await generateText({
model: openai('gpt-4o'),
tools: {
webSearch: webSearchTool,
scrapePage: scrapePageTool,
},
maxSteps: 10,
system:
You are a thorough research agent.Search for information on the given topic. Visit the most relevant pages. Synthesize a comprehensive, well-cited summary. Always verify information from multiple sources before concluding.
prompt:
Research the following topic and provide a detailed summary: ${topic},onStepFinish: ({ stepType, toolCalls, toolResults, text }) => {
console.log(
Step type: ${stepType});if (toolCalls) console.log(
Tools called: ${toolCalls.map(t => t.toolName).join(', ')});},
});
return { summary: text, totalSteps: steps.length };
}
Tracking Agent Steps
The steps array returned by generateText gives you full visibility into what the agent did:
const { text, steps } = await generateText({ ... });
for (const step of steps) {
console.log('Step type:', step.stepType); // 'initial' | 'continue' | 'tool-result'
console.log('Text so far:', step.text);
console.log('Tool calls:', step.toolCalls);
console.log('Token usage:', step.usage);
}
Streaming Agent Responses to the UI
// app/api/research/route.ts
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { webSearchTool, scrapePageTool } from '@/lib/tools';
export async function POST(req: Request) {
const { topic } = await req.json();
const result = await streamText({
model: openai('gpt-4o'),
tools: { webSearch: webSearchTool, scrapePage: scrapePageTool },
maxSteps: 8,
system: 'You are a research assistant. Search the web and synthesize findings.',
prompt: Research: ${topic},
});
return result.toDataStreamResponse();
}
The streaming agent will interleave tool call events and text tokens in the SSE stream. The useChat hook handles rendering these automatically.
RAG: Retrieval Augmented Generation Integration
RAG grounds your LLM's answers in your own data — documents, database records, knowledge bases — by retrieving relevant context at query time and injecting it into the prompt.
The RAG Pipeline
A standard RAG pipeline has these steps:
Embedding with the AI SDK
// lib/embeddings.ts
import { embed, embedMany } from 'ai';
import { openai } from '@ai-sdk/openai';
const embeddingModel = openai.embedding('text-embedding-3-small');
export async function embedText(text: string): Promise {
const { embedding } = await embed({
model: embeddingModel,
value: text,
});
return embedding;
}
export async function embedBatch(texts: string[]): Promise {
const { embeddings } = await embedMany({
model: embeddingModel,
values: texts,
});
return embeddings;
}
Document Ingestion
// scripts/ingest-documents.ts
import { embedBatch } from '@/lib/embeddings';
import { createClient } from '@supabase/supabase-js';
import fs from 'fs/promises';
const supabase = createClient(
process.env.NEXTPUBLICSUPABASEURL!,
process.env.SUPABASESERVICEKEY!
);
function chunkText(text: string, chunkSize = 500, overlap = 50): string[] {
const chunks: string[] = [];
let start = 0;
while (start < text.length) {
chunks.push(text.slice(start, start + chunkSize));
start += chunkSize - overlap;
}
return chunks;
}
async function ingestDocument(filePath: string, source: string) {
const content = await fs.readFile(filePath, 'utf-8');
const chunks = chunkText(content);
const embeddings = await embedBatch(chunks);
const rows = chunks.map((chunk, i) => ({
content: chunk,
embedding: embeddings[i],
source,
chunkindex: i,
}));
const { error } = await supabase.from('documents').insert(rows);
if (error) throw error;
console.log(Ingested ${rows.length} chunks from ${source});
}
await ingestDocument('./docs/company-faq.txt', 'company-faq');
Retrieval and Generation
// app/api/rag-chat/route.ts,import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { embedText } from '@/lib/embeddings';
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(
process.env.NEXTPUBLICSUPABASEURL!,
process.env.SUPABASESERVICEKEY!
);
async function retrieveContext(query: string, topK = 5): Promise
{ const queryEmbedding = await embedText(query);
// Using Supabase pgvector for similarity search
const { data, error } = await supabase.rpc('matchdocuments', {
queryembedding: queryEmbedding,
matchcount: topK,
matchthreshold: 0.7,
});
if (error) throw error;
return data.map((doc: { content: string }) => doc.content).join('\n\n');
}
export async function POST(req: Request) {
const { messages } = await req.json();
const lastUserMessage = messages[messages.length - 1].content;
// Retrieve relevant context
const context = await retrieveContext(lastUserMessage);
const result = await streamText({
model: openai('gpt-4o'),
system:
You are a helpful assistant with access to the company knowledge base.Answer questions based on the following context. If the context does not contain enough information to answer confidently, say so clearly.
CONTEXT:
${context}
messages,
});
return result.toDataStreamResponse();
}
Supabase pgvector Setup
The SQL to set up vector search in Supabase:
-- Enable the pgvector extension
create extension if not exists vector;
-- Create the documents table
create table documents (
id bigserial primary key,
content text not null,
embedding vector(1536), -- Dimension for text-embedding-3-small
source text,
chunkindex int,
createdat timestamptz default now()
);
-- Create an index for fast similarity search
create index on documents using ivfflat (embedding vectorcosineops)
with (lists = 100);
-- Create the match function
create or replace function matchdocuments(
queryembedding vector(1536),
matchcount int default 5,
matchthreshold float default 0.7
)
returns table (id bigint, content text, source text, similarity float)
language sql stable
as $
select id, content, source,
1 - (embedding <=> queryembedding) as similarity
from documents
where 1 - (embedding <=> queryembedding) > matchthreshold
order by embedding <=> queryembedding
limit matchcount;
$;
Best Practices
1. Always Validate Structured Outputs
Even with generateObject, validate the returned data before using it in your application:
const { object } = await generateObject({ model, schema: ProductSchema, prompt });
// Additional business-logic validation beyond schema
if (object.price > 10000) {
throw new Error('Price seems unrealistically high — please review.');
}
2. Implement Retry Logic and Error Handling
LLM APIs can fail transiently. Wrap calls with retry logic:
import { generateText } from 'ai';
async function generateWithRetry(params: Parameters[0], maxAttempts = 3) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await generateText(params);
} catch (error) {
if (attempt === maxAttempts) throw error;
const delay = Math.pow(2, attempt) 500; // Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
3. Stream Responses for Better UX
Always prefer streamText over generateText for user-facing chat and generation features. Streaming reduces perceived latency dramatically, especially for long responses.
4. Use Model-Specific Strengths
Different providers excel at different tasks:
// For reasoning-heavy tasks
const reasoningResult = await generateText({
model: openai('o1-preview'),
prompt: complexReasoningPrompt,
});
// For long-context document analysis
const docResult = await generateText({
model: google('gemini-1.5-pro'),
prompt: longDocumentPrompt,
});
// For creative writing and nuanced tasks
const creativeResult = await generateText({
model: anthropic('claude-3-5-sonnet-20241022'),
prompt: creativeWritingPrompt,
});
5. Control Costs with Token Limits
Always set maxTokens to avoid runaway costs:
const result = await generateText({
model: openai('gpt-4o'),
prompt,
maxTokens: 1024, // Hard cap on output tokens
temperature: 0.3, // Lower = more deterministic
});
6. Log Token Usage for Monitoring
const { text, usage } = await generateText({ model, prompt });
console.log({
promptTokens: usage.promptTokens,
completionTokens: usage.completionTokens,
totalTokens: usage.totalTokens,
});
// Send to your analytics/monitoring service
await trackUsage({ model: 'gpt-4o', ...usage });
7. Secure Your API Routes
Do not expose your AI endpoints without authentication:
// app/api/chat/route.ts
import { auth } from '@/lib/auth'; // Your auth solution
export async function POST(req: Request) {
const session = await auth();
if (!session?.user) {
return new Response('Unauthorized', { status: 401 });
}
// Rate limiting per user
const isAllowed = await checkRateLimit(session.user.id);
if (!isAllowed) {
return new Response('Too Many Requests', { status: 429 });
}
// ... proceed with AI call
}
8. Use System Prompts Consistently
A well-crafted system prompt dramatically improves output quality and consistency. Keep them in a dedicated file:
// lib/system-prompts.ts
export const CUSTOMERSUPPORTPROMPT =
You are a customer support agent for PT RUBYTHALIB DATA KONSULTA.
- Always be professional, concise, and helpful.
- If you do not know something, say so and offer to escalate to a human agent.
- Do not make promises about pricing or timelines without checking current data.
- Respond in the same language the user writes in.
.trim();
9. Handle Abort Signals for Cancellation
Allow users to cancel in-progress requests:
// In your route handler
export async function POST(req: Request) {
const result = await streamText({
model: openai('gpt-4o'),
messages,
abortSignal: req.signal, // Pass the request's abort signal
});
return result.toDataStreamResponse();
}
The useChat hook provides a stop() function that triggers request cancellation.
10. Test with Multiple Providers
Since the AI SDK abstracts provider differences, testing your app with multiple providers is easy. This is valuable for cost optimization and fallback strategies:
const providers = [
openai('gpt-4o'),
anthropic('claude-3-5-sonnet-20241022'),
google('gemini-1.5-pro'),
];
// Fallback to the next provider if the first fails
for (const model of providers) {
try {
const { text } = await generateText({ model, prompt });
return text;
} catch {
continue;
}
}
Conclusion
The Vercel AI SDK is a mature, well-designed toolkit that dramatically reduces the complexity of building AI-powered web applications. By providing a consistent interface across providers, first-class TypeScript support, React hooks for real-time streaming, and powerful primitives like structured output and tool calling, it covers the full spectrum from simple text generation to sophisticated autonomous agents.
Here is a summary of what we covered:
- generateText / streamText: The core building blocks for one-shot generation and streaming chat
- useChat / useCompletion: React hooks that connect your UI to streaming endpoints with minimal code
- generateObject / streamObject: Type-safe structured output using Zod schemas, eliminating fragile JSON parsing
- Tool calling: Extending LLM capabilities with external functions and APIs using the
toolhelper - Multi-step agents: Autonomous loops that use
maxStepsto let the model reason, act, observe, and iterate - RAG: Grounding LLM responses in your own data through embedding, vector search, and context injection
- Best practices: Rate limiting, error handling, cost control, authentication, and provider diversity
The AI SDK continues to evolve rapidly, with new features such as computer use, vision inputs, and advanced multi-modal capabilities being added regularly. The official documentation at sdk.vercel.ai is the best place to stay current.
If you are starting a new AI feature today, the Vercel AI SDK should be your first choice for the Node.js and Next.js ecosystem. It lets you focus on the product experience rather than the infrastructure plumbing — and that is exactly the kind of leverage that matters when shipping fast.
Happy building.
Ruby Abdullah PT RUBYTHALIB DATA KONSULTA Jakarta, November 2026