Skip to content
, ,

Vercel AI SDK Tutorial: Build AI Apps in TypeScript (v7 Guide)

11โ€“17 minutes
Smiling woman in a server room holding a tablet showing AI SDK, with the text AI SDK 7 - FREE TOOLKIT

Vercel’s AI SDK is a free, open-source TypeScript toolkit that lets you call OpenAI, Anthropic, Google and hundreds of other models with one API. Version 7 is the current major, and 7.1 landed on 3 December 2026.

In this tutorial I walk you through the whole thing: install, text and streaming, tools, structured output, a Next.js chat UI with useChat, AI Gateway, costs and the errors you will actually hit.

TLDR

  • Current version: ai 7.1.1 (checked 5 Dec 2026). v7 shipped on 25 June 2026 and needs Node.js 22+. It is ESM-only.
  • Install: npm install ai zod, plus @ai-sdk/openai, @ai-sdk/anthropic or @ai-sdk/google if you want direct provider keys.
  • Core calls: generateText and streamText. Structured output now uses output: Output.object(); generateObject is deprecated.
  • v7 renames: system became instructions, stepCountIs became isStepCount, onFinish became onEnd.
  • Cost: the SDK is free (Apache 2.0). You only pay model tokens. AI Gateway adds no token markup and includes $5/month free credit.

What the AI SDK Is and When to Use It

The AI SDK is a library from the team behind Next.js. It gives you one set of functions for text, streaming, tools, structured data, images, speech and agents. You swap the model string and the rest of your code stays the same.

Vercel says the package passes 16 million weekly downloads. It has three main layers:

  • AI SDK Core (ai): server-side functions such as generateText, streamText, embed and ToolLoopAgent.
  • AI SDK UI (@ai-sdk/react, Vue, Svelte, Angular): hooks like useChat that handle chat state and streaming for you.
  • Providers (@ai-sdk/*): adapters for OpenAI, Anthropic, Google and more, plus the built-in Vercel AI Gateway provider.
Quick answer: pick the AI SDK when you build in TypeScript and want to switch models without rewriting code, or need a streaming chat UI fast. If you only ever call one provider from Python, that provider’s own SDK is simpler (see my Claude API Python tutorial).

Prerequisites

  • Node.js 22 or newer: v7 dropped Node 18 and 20. Vercel recommends Node 24 LTS or 26 for production.
  • An ESM project: add "type": "module" to package.json or use .mjs files. require() no longer works.
  • One API key: either a Vercel AI Gateway key, or a provider key from OpenAI, Anthropic or Google.
  • Zod: version 3.25.76+ or 4.1.8+ (the peer range listed by the ai package).

Install and Set Up Keys

Here is the fastest path for a plain Node.js script. The Next.js version comes later in this guide.

  1. Create a project. Run mkdir ai-demo && cd ai-demo, then npm init -y and set "type": "module" in package.json.
  2. Install the SDK. Run npm install ai zod dotenv. The AI Gateway provider ships inside ai.
  3. Add TypeScript tooling. Run npm install -D typescript tsx @types/node so you can run .ts files with npx tsx.
  4. Add provider packages (optional). For direct keys, run npm install @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google.
  5. Create .env. Add only the keys you use: AI_GATEWAY_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY.
  6. Keep keys out of Git. Add .env to .gitignore. Never paste a key into source code.
GitHub release page for vercel/ai showing ai@7.1.0 with harnesses and tools, typed decisions, batch processing and steering
Official vercel/ai GitHub release page for ai@7.1.0 (checked 5 Dec 2026).

Tip: using a coding agent? The official README suggests npx skills add vercel/ai so the agent learns the v7 API instead of older patterns.

generateText: Your First Call

generateText waits for the full answer and returns it. Use it for scripts, background jobs, summaries and agents that call tools.

// hello.ts  (run with: npx tsx hello.ts)
import 'dotenv/config';
import { generateText } from 'ai';

const result = await generateText({
  model: 'anthropic/claude-sonnet-5.5', // AI Gateway model string
  instructions: 'You are a friendly teacher. Answer in 3 short sentences.',
  prompt: 'What is an API rate limit?',
});

console.log(result.text);
console.log(result.usage); // inputTokens, outputTokens, totalTokens (all steps)
console.log(result.finishReason);

A plain string like 'anthropic/claude-sonnet-5.5' goes through the Vercel AI Gateway, which is the default global provider. It reads AI_GATEWAY_API_KEY from the environment.

Note: in v7 the system prompt option is called instructions. Older tutorials that use system: are written for v6 or earlier.

streamText: Streaming Output

streamText starts returning tokens right away, which is what you want for chat and any UI. It does not need await on the call itself.

// stream.ts
import 'dotenv/config';
import { streamText } from 'ai';

const result = streamText({
  model: 'anthropic/claude-sonnet-5.5',
  prompt: 'Explain WebSockets to a beginner in 5 bullet points.',
  onError({ error }) {
    console.error('Stream error:', error); // errors do not throw here
  },
});

for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}

console.log('Tokens used:', await result.usage);

Two v7 details matter. The full event stream is now result.stream (it used to be fullStream). And streamText suppresses errors so your server does not crash, so always add onError.

Provider Packages: OpenAI, Anthropic, Google

If you already have provider keys, skip the gateway and import a provider directly. Each package reads its own environment variable.

Provider Package (version checked) Env variable Example model ID
OpenAI @ai-sdk/openai 4.0.130 OPENAI_API_KEY gpt-6.2-sol
Anthropic @ai-sdk/anthropic 4.0.115 ANTHROPIC_API_KEY claude-sonnet-5-5
Google (Gemini API) @ai-sdk/google 4.0.133 GOOGLE_GENERATIVE_AI_API_KEY gemini-4-hydrogen
Vercel AI Gateway built into ai (or @ai-sdk/gateway 4.0.163) AI_GATEWAY_API_KEY anthropic/claude-sonnet-5.5
// providers.ts
import 'dotenv/config';
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { anthropic } from '@ai-sdk/anthropic';
import { google } from '@ai-sdk/google';

const models = [
  openai('gpt-6.2-sol'),
  anthropic('claude-sonnet-5-5'),
  google('gemini-4-hydrogen'),
];

for (const model of models) {
  const { text } = await generateText({
    model,
    prompt: 'Give me one tip for writing clean TypeScript.',
  });
  console.log(model.modelId, '->', text);
}

Notice the ID formats differ. Direct Anthropic IDs use dashes (claude-sonnet-5-5), while gateway strings use the creator/model form with a dot (anthropic/claude-sonnet-5.5). Need a custom base URL or key? Use createOpenAI, createAnthropic or createGoogleGenerativeAI.

Warning: gemini-4-argon is deprecated. From 15 December 2026, Google routes it to Gemini 4 Carbon at Carbon rates ($4 / $20 per million tokens). Pick a current model instead.

Tools and Multi-Step Calls

Tools let the model call your functions, such as a weather lookup or a database query. You define each tool with a description, a Zod inputSchema and an execute function.

By default, generation stops after one step (isStepCount(1)). So the model calls the tool and stops without a final answer. Set stopWhen to let it read the tool result and keep going.

// tools.ts
import 'dotenv/config';
import { generateText, tool, isStepCount } from 'ai';
import { z } from 'zod';

const { text, steps } = await generateText({
  model: 'anthropic/claude-sonnet-5.5',
  tools: {
    weather: tool({
      description: 'Get the current temperature for a city in Celsius',
      inputSchema: z.object({
        city: z.string().describe('City name, for example Paris'),
      }),
      execute: async ({ city }) => {
        // call a real weather API here
        return { city, temperatureC: 18 };
      },
    }),
  },
  stopWhen: isStepCount(5), // up to 5 steps while tools are being called
  prompt: 'Is it jacket weather in Paris right now?',
});

console.log(text);
console.log('Tool calls:', steps.flatMap(s => s.toolCalls).length);

Other stop conditions include hasToolCall('toolName'), which stops once a named tool runs. Use onStepEnd to log each step. For a reusable agent, wrap the same settings in new ToolLoopAgent({...}).

Structured Output with Output.object

Since v6, structured data is part of generateText and streamText. You pass output: Output.object({ schema }) and read result.output. The old generateObject and streamObject still exist but are deprecated.

// extract.ts
import 'dotenv/config';
import { generateText, Output, NoObjectGeneratedError } from 'ai';
import { z } from 'zod';

const Invoice = z.object({
  vendor: z.string(),
  total: z.number(),
  currency: z.string().length(3),
  lineItems: z.array(z.object({ name: z.string(), amount: z.number() })),
});

try {
  const { output } = await generateText({
    model: 'google/gemini-4-hydrogen',
    output: Output.object({ schema: Invoice }),
    prompt: 'Extract: ACME Ltd billed 2 domains at 12 USD and hosting at 30 USD.',
  });
  console.log(output.total, output.lineItems);
} catch (error) {
  if (NoObjectGeneratedError.isInstance(error)) {
    console.error('Model output did not match the schema:', error.text);
  } else {
    throw error;
  }
}

Other output types are Output.array({ element }), Output.choice() for classification and Output.text(). For streaming JSON, use streamText with output and loop over partialOutputStream. For provider-level details, see my structured outputs guide.

Build a Next.js Chat UI with useChat

This is the classic AI SDK use case. A route handler streams from the model, and the useChat hook renders messages as they arrive.

  1. Create the app. Run npx create-next-app@latest my-ai-app and choose the App Router.
  2. Install packages. In the folder, run npm install ai @ai-sdk/react zod.
  3. Add your key. Put AI_GATEWAY_API_KEY=... in .env.local.
  4. Create the route. Add app/api/chat/route.ts with the code below.
  5. Replace the page. Paste the client component into app/page.tsx.
  6. Run it. Start npm run dev and open http://localhost:3000.

The route handler (app/api/chat/route.ts)

import {
  streamText,
  UIMessage,
  convertToModelMessages,
  createUIMessageStreamResponse,
  toUIMessageStream,
} from 'ai';

export const maxDuration = 60; // seconds, for Vercel deployments

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();

  const result = streamText({
    model: 'anthropic/claude-sonnet-5.5',
    instructions: 'You are a helpful assistant. Keep answers short.',
    messages: await convertToModelMessages(messages),
  });

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  });
}

Note: result.toUIMessageStreamResponse() still works in v7 but is deprecated. The official quickstart now uses the stateless createUIMessageStreamResponse plus toUIMessageStream helpers shown above.

The chat page (app/page.tsx)

'use client';

import { useChat } from '@ai-sdk/react';
import { useState } from 'react';

export default function Chat() {
  const [input, setInput] = useState('');
  const { messages, sendMessage, status, stop, error } = useChat();

  return (
    <main style={{ maxWidth: 640, margin: '40px auto' }}>
      {messages.map(m => (
        <div key={m.id}>
          <strong>{m.role === 'user' ? 'You: ' : 'AI: '}</strong>
          {m.parts.map((part, i) =>
            part.type === 'text' ? <span key={i}>{part.text}</span> : null,
          )}
        </div>
      ))}

      {error && <p>Something went wrong. Please try again.</p>}

      <form
        onSubmit={e => {
          e.preventDefault();
          if (!input.trim()) return;
          sendMessage({ text: input });
          setInput('');
        }}
      >
        <input
          value={input}
          onChange={e => setInput(e.target.value)}
          disabled={status !== 'ready'}
          placeholder="Ask something..."
        />
        {status === 'streaming' ? (
          <button type="button" onClick={stop}>Stop</button>
        ) : (
          <button type="submit" disabled={status !== 'ready'}>Send</button>
        )}
      </form>
    </main>
  );
}

useChat posts to /api/chat by default. Its status moves through submitted, streaming, ready and error. Messages arrive as parts, so tool calls show up as parts named tool-yourToolName.

To add tools to the chat, put the same tools and stopWhen from the earlier section inside streamText in the route. Then render the tool parts in the page.

AI Gateway: One Key for Every Model

The Vercel AI Gateway is a hosted router. One key reaches models from OpenAI, Anthropic, Google, xAI and many others, with automatic retries across providers. You do not need to deploy on Vercel to use it.

  • Pricing: no markup and no platform fee on tokens. You pay the provider’s list price from prepaid AI Gateway Credits.
  • Free tier: $5/month of included credit on a subset of models, with lower per-model rate limits. It is a monthly credit, not a trial.
  • BYOK: bring your own provider keys on the paid tier with no inference markup.
  • Extras: budgets, logs, model fallbacks and optional add-ons such as team-wide zero data retention, which carry their own fees.
Vercel AI Gateway pricing docs showing no markup and no platform fee on tokens and a $5 per month included free credit
Official Vercel AI Gateway pricing docs (checked 5 Dec 2026).

You can check the model catalog with a single curl call. This endpoint needs no key:

curl -s https://ai-gateway.vercel.sh/v1/models | head -c 600

To check your remaining balance, call GET https://ai-gateway.vercel.sh/v1/credits with an Authorization: Bearer $AI_GATEWAY_API_KEY header. If you compare routers, my OpenRouter guide covers the main alternative.

Costs and a Worked Example

The SDK itself costs nothing. It is open source under the Apache 2.0 licence. Your bill is the model tokens, billed by the provider or by AI Gateway at list price.

Model Input / 1M tokens Output / 1M tokens Notes
Claude Haiku 5.5 $0.10 $0.50 Prompts up to 100K tokens
Claude Sonnet 5.5 $2.00 $10.00 Cache reads $0.10
Claude Opus 5.5 $4.00 $20.00 Cache reads $0.20
GPT-6.2 Sol $2.00 $10.00 Cached input $0.10
GPT-6.2 Astra $8.00 $40.00 Cached input $0.40
Gemini 4 Hydrogen $1.50 $7.50 Free tier available on the Gemini API
Gemini 4 Carbon $4.00 $20.00 Paid tier only; price rose on 1 Dec 2026

Prices are standard-tier list prices from the official pages, checked 5 December 2026. Full breakdowns are in my Claude API pricing, OpenAI API pricing and Gemini API pricing guides.

Worked example: a small support chatbot

Say your chat route handles 1,000 messages a day. Each one sends about 1,500 input tokens (history plus instructions) and gets 500 output tokens back.

  • Claude Sonnet 5.5 or GPT-6.2 Sol: (1,500 x $2 + 500 x $10) / 1M = $0.008 per message, so about $8 a day or $240 over 30 days.
  • Gemini 4 Hydrogen: (1,500 x $1.50 + 500 x $7.50) / 1M = $0.006 per message, so about $6 a day.
  • Claude Haiku 5.5: (1,500 x $0.10 + 500 x $0.50) / 1M = $0.0004 per message, so about $0.40 a day.

Prompt caching can cut the input part a lot for long, repeated instructions. See prompt caching explained for how each provider handles it.

Limits and Defaults to Know

Setting Value What it means for you
Node.js 22+ (tested on 22, 24, 26) Older runtimes fail to install or run
Module format ESM only Use import, not require()
maxRetries 2 by default Set 0 to disable automatic retries
stopWhen isStepCount(1) by default Raise it or tools never get a final answer
Vercel function maxDuration Above 300 s needs Pro or Enterprise Long agent runs can time out on Hobby
AI Gateway free tier $5/month, subset of models, lower rate limits Expect 429 errors under load
AI Gateway credits Expire 1 year after purchase Do not over-buy
Provider rate limits Set by each provider tier See LLM API rate limits

What Changed in v7 and 7.1

If you are coming from v5 or v6 code, these are the renames that break builds most often:

  • system to instructions: applies to generateText, streamText and the object functions.
  • stepCountIs to isStepCount: update your stopWhen imports.
  • onFinish to onEnd and onStepFinish to onStepEnd: lifecycle callbacks were renamed.
  • usage now covers all steps: use result.finalStep.usage for the last step only. totalUsage is deprecated.
  • Telemetry moved: OpenTelemetry now lives in @ai-sdk/otel.

The official codemod does most of this for you: npx @ai-sdk/codemod v7. Version 7.1 (3 December 2026) then added harness adapters for Cline, Cursor and GitHub Copilot, @ai-sdk/tool-bash and @ai-sdk/tool-web-fetch, batch processing helpers, steering for running agents and async video generation. Most of these are still marked experimental_.

Troubleshooting: Common Problems and Fixes

Error or symptom Likely cause Fix
AI_LoadAPIKeyError The provider env variable is missing or not loaded Check the exact name (for example GOOGLE_GENERATIVE_AI_API_KEY) and load dotenv/config first
AI_APICallError with status 401 Wrong, revoked or wrong-provider key Create a new key; check statusCode and responseBody on the error
AI_APICallError or gateway 429 Rate limit hit (free tier limits are lower) Back off and retry; buy credits or raise your provider tier
Gateway 402 No positive AI Gateway Credits balance, or a budget was reached Top up credits or raise the budget
Gateway 403 customer_verification_required No payment method on the team Add a payment method before using free credits
AI_NoObjectGeneratedError Model output failed your Zod schema Loosen the schema, use a stronger model, or log error.text
AI_NoOutputGeneratedError Final step ended with tool calls, not text Raise stopWhen so the model can finish
Blank chat reply after a tool call Default single step Add stopWhen: isStepCount(5) in the route
stepCountIs is not exported v6 code on v7 Rename to isStepCount or run the codemod
Stream works locally, times out on Vercel Function hit maxDuration Export a higher maxDuration in the route file

For catching errors in code, every AI SDK error class has an isInstance() check, such as APICallError.isInstance(error). Provider-specific error codes are covered in my Claude API errors and OpenAI API errors guides.

Frequently Asked Questions

Is the Vercel AI SDK free?

Yes. The ai package and its provider packages are free and open source under Apache 2.0. You only pay for model tokens, either to the provider or through AI Gateway at list price.

What is the latest version of the AI SDK?

As of 5 December 2026 the latest release is ai 7.1.1. Version 7.0 came out on 25 June 2026 and 7.1.0 on 3 December 2026.

Do I need to deploy on Vercel to use it?

No. The SDK runs in any Node.js 22+ environment, and AI Gateway keys work from local machines, CI and other clouds. Vercel is only needed to create the gateway key and manage billing.

Is generateObject removed?

Not removed, but deprecated. The recommended way is generateText or streamText with output: Output.object({ schema }), which also works alongside tools.

Can I use the AI SDK without AI Gateway?

Yes. Install @ai-sdk/openai, @ai-sdk/anthropic or @ai-sdk/google and pass a provider model such as anthropic('claude-sonnet-5-5'). Your own provider key is then billed directly.

Does the AI SDK work with Python?

The main AI SDK is TypeScript. Vercel documents a separate AI SDK for Python for AI Gateway, and Python apps can also call the gateway through the OpenAI or Anthropic SDKs by changing the base URL.

How do I upgrade from v6 to v7?

Move to Node.js 22+, switch to ESM, then run npx @ai-sdk/codemod v7. Check the renames it misses, such as system to instructions, by reading the official migration guide.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Smiling woman in a server room holding a tablet showing AI SDK, with the text AI SDK 7 - FREE TOOLKIT