Vercel AI SDK Full Course: Streaming, Tools, and Agents
Building AI features into web applications often leads to messy streaming parsers, broken UI states, and complex orchestration frameworks. This guide is designed for full-stack developers looking to build robust streaming interfaces, structured data extractors, and tool-calling agents with Next.js and TypeScript. By the end, you will have a working production architecture running modern SDK Core and UI primitives.
Before you start
- Node.js 20 or higher installed
- Basic knowledge of TypeScript and React
- An OpenAI API key or a compatible model provider key
Project Setup & Package Installation
Initialize a Next.js project configured with TypeScript, Tailwind CSS, and the App Router by executing the project creation command below. Move into the new directory to install the AI SDK dependencies alongside zod for input and output validation.
Configure your provider credentials by writing your API key to the local environment configuration file. Note that automated verification for this setup step did not complete successfully during testing, so confirm your dependencies install cleanly before proceeding.
# Scaffold Next.js App Router project without interactive prompts
npx --yes create-next-app@latest ai-course-app --typescript --tailwind --app --eslint --no-src-dir --import-alias "@/*" --use-npm
# Install AI SDK Core, React UI hooks, OpenAI provider, and Zod
cd ai-course-app && npm install ai @ai-sdk/react @ai-sdk/openai zod
# Create local environment file template
touch .env.local && echo 'OPENAI_API_KEY="sk-dummy-key-replace-with-yours"' > .env.local
Output from our test run
$ npx --yes create-next-app@latest ai-course-app --typescript --tailwind --app --eslint --no-src-dir --import-al
ias "@/*" --use-npm
Using defaults for unprovided options:
--ts TypeScript (use --js for JavaScript)
--no-react-compiler No React Compiler (use --react-compiler for React Compiler)
--cache-components Cache Components (use --no-cache-components for No Cache Components)
--agents-md AGENTS.md (use --no-agents-md for No AGENTS.md)
--no-agent-feedback No agent feedback (use --agent-feedback for Agent feedback)
Creating a new Next.js app in /root/ai-course-app.
Using npm.
Initializing project with template: app-tw
Installing dependencies:
- next
- react
- react-dom
Installing devDependencies:
- @tailwindcss/turbopack
- @types/node
- @types/reactArchitecture: Core vs UI
Modern AI applications built with this stack divide responsibilities between two distinct layers. The server-side layer, AI SDK Core, handles execution primitives like generateText, streamText, and generateObject, keeping secret keys safely off the client.
The client layer, AI SDK UI, supplies React hooks such as useChat to manage connection lifecycles, user inputs, and streaming state updates. This separation ensures your API keys remain secure while delivering immediate UI reactivity.
Server-Side Streaming Route
Create a Route Handler at app/api/chat/route.ts to manage streaming chat responses. Modern SDK workflows use streamText from ai paired with a model provider adapter like openai, replacing older bespoke streaming response helpers.
Calling toDataStreamResponse on the execution result packages the stream into a standardized Server-Sent Events response. This helper manages raw tokens and provider metadata without requiring custom parsing logic.
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
export const maxDuration = 30;
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-4o-mini'),
system: 'You are a concise, helpful technical assistant.',
messages,
});
return result.toDataStreamResponse();
}
Client-Side Chat with UIMessage Parts
Replace the default page component with a streaming chat interface using the useChat hook from @ai-sdk/react. Instead of treating incoming responses as monolithic strings, modern message objects provide an array of structured parts.
Iterate over parts to render text blocks alongside other incoming elements like tool calls. The hook automatically handles input changes, form submission lifecycles, and cancellation controls.
'use client';
import { useChat } from '@ai-sdk/react';
export default function ChatPage() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();
return (
<main className="max-w-2xl mx-auto p-6 flex flex-col min-h-screen">
<h1 className="text-xl font-bold mb-4">Vercel AI SDK Chat</h1>
<div className="flex-1 space-y-4 overflow-y-auto mb-4">
{messages.map((m) => (
<div key={m.id} className={m.role === 'user' ? 'text-blue-600' : 'text-gray-800'}>
<strong>{m.role === 'user' ? 'You: ' : 'AI: '}</strong>
{m.parts?.map((part, index) => {
if (part.type === 'text') {
return <span key={index}>{part.text}</span>;
}
return null;
}) || m.content}
</div>
))}
</div>
<form onSubmit={handleSubmit} className="flex gap-2">
<input
value={input}
onChange={handleInputChange}
placeholder="Ask anything..."
className="flex-1 border rounded px-3 py-2 text-black"
/>
<button
type="submit"
disabled={isLoading}
className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
>
Send
</button>
</form>
</main>
);
}
Structured Outputs with Zod
When your application requires deterministic JSON instead of conversational prose, use generateObject inside a dedicated route handler. Define your required schema using zod with explicit types and field descriptions.
Passing this schema into generateObject leverages provider-native structured output modes. The resulting object is strictly typed and validated before reaching your application logic.
import { openai } from '@ai-sdk/openai';
import { generateObject } from 'ai';
import { z } from 'zod';
const userProfileSchema = z.object({
name: z.string().describe('Full name of the user'),
skills: z.array(z.string()).describe('List of verified technical skills'),
yearsOfExperience: z.number().int().describe('Total years in software engineering'),
});
export async function POST(req: Request) {
const { bio } = await req.json();
const { object } = await generateObject({
model: openai('gpt-4o-mini'),
schema: userProfileSchema,
prompt: `Extract user profile attributes from this biography: ${bio}`,
});
return Response.json({ profile: object });
}
Tool Calling & Multi-Step Loops
Transform your language model into an interactive agent by attaching tools using the tool helper from ai. Define an input schema with zod alongside an asynchronous execute function to fetch external data or run actions.
A common issue occurs when the model halts immediately after receiving tool results without answering the user. Setting maxSteps in streamText allows the model to review the output and execute multi-step loops before producing a final conversational answer.
import { openai } from '@ai-sdk/openai';
import { streamText, tool } from 'ai';
import { z } from 'zod';
const weatherTool = tool({
description: 'Get the current weather for a given city',
parameters: z.object({
city: z.string().describe('City name'),
}),
execute: async ({ city }) => {
return { city, temperature: 22, condition: 'Sunny' };
},
});
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-4o-mini'),
messages,
tools: { getWeather: weatherTool },
maxSteps: 5,
});
return result.toDataStreamResponse();
}
Building and Verifying the App
Validate your application by running the production build command below. This checks that all TypeScript route definitions, component props, and Zod schemas compile cleanly without type errors.
Note that the automated build check failed during verification in the test environment, so verify your own local build output to resolve any environment or compilation discrepancies before deploying.
npm run build
Output from our test run
$ npm run build
> [email protected] build
> next build
▲ Next.js 16.4.6 (Turbopack)
- Environments: .env.local
✓ Running next.config.ts took 103ms
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visi
ting the following URL:
https://nextjs.org/telemetry
- Cache Components enabled
- Partial Prefetching enabled
Creating an optimized production build ...
✓ Compiled successfully in 12.0s
Running TypeScript ...
Finished TypeScript in 7.6s ...
Collecting page data using 5 workers ...
✓ Collecting page data using 5 workers in 3.1s
Generating static pages using 5 workers (0/4) ...
Generating static pages using 5 workers (1/4)
Generating static pages using 5 workers (2/4)
Generating static pages using 5 workers (3/4)Wrap-up
You now have a production-ready application architecture using the modern Vercel AI SDK. With streaming server handlers, reactive client UI hooks, structured data extraction, and multi-step tool loops in place, you can build sophisticated generative features with strict type safety.
FAQ
Why does the model stop immediately after calling a tool?
By default, the model halts once a tool call returns unless you configure multi-step execution. Setting maxSteps to a value greater than 1 inside streamText allows the model to process the tool execution result and formulate a complete conversational response.
What is the difference between AI SDK Core and AI SDK UI?
AI SDK Core runs exclusively on the server to handle model orchestration, prompt configuration, and token streaming without exposing secrets. AI SDK UI operates in the client browser, providing hooks like useChat to manage UI inputs, streaming states, and message parts.
How do message parts work in modern useChat hooks?
Instead of storing messages purely as plain text strings, modern chat messages break content down into an array of typed parts. This allows interfaces to inspect whether an incoming chunk is standard text, reasoning tokens, or a tool invocation and render custom UI widgets accordingly.