VercelVercel
Menu

AI SDK

Last updated January 3, 2026

The AI SDK is the recommended way to build AI-powered TypeScript applications with AI Gateway. Pass a model string like 'anthropic/claude-sonnet-4.6' directly to AI SDK functions and requests route through AI Gateway automatically.

Install the ai package:

Terminal
npm install ai
Terminal
yarn add ai
Terminal
pnpm add ai
Terminal
bun add ai

Generate text by passing a plain string model ID. AI Gateway resolves the provider and routes the request automatically.

index.ts
import { generateText } from 'ai';
 
const { text } = await generateText({
  model: 'anthropic/claude-sonnet-4.6',
  prompt: 'Explain quantum computing in one paragraph.',
});
 
console.log(text);

Stream responses token-by-token for real-time output:

stream.ts
import { streamText } from 'ai';
 
const result = streamText({
  model: 'openai/gpt-5.4',
  prompt: 'Write a short story about a robot discovering music.',
});
 
for await (const textPart of result.textStream) {
  process.stdout.write(textPart);
}

Generate type-safe structured data with generateObject and a Zod schema:

structured.ts
import { generateObject } from 'ai';
import { z } from 'zod';
 
const { object } = await generateObject({
  model: 'anthropic/claude-sonnet-4.6',
  schema: z.object({
    name: z.string(),
    age: z.number(),
    city: z.string(),
  }),
  prompt: 'Extract: John is 30 years old and lives in NYC.',
});
 
console.log(object); // { name: 'John', age: 30, city: 'NYC' }

Define tools that models can invoke to interact with external systems:

tools.ts
import { generateText, tool } from 'ai';
import { z } from 'zod';
 
const { text, toolResults } = await generateText({
  model: 'anthropic/claude-sonnet-4.6',
  tools: {
    getWeather: tool({
      description: 'Get the current weather for a location',
      parameters: z.object({
        location: z.string().describe('City name, e.g. San Francisco'),
      }),
      execute: async ({ location }) => ({
        location,
        temperature: 72,
        condition: 'sunny',
      }),
    }),
  },
  prompt: "What's the weather in Tokyo?",
});
 
console.log(text);

AI Gateway works with both AI SDK v5 and v6. All core features (text generation, streaming, structured outputs, tool calling) work across both versions.

AI SDK v6 adds support for additional capabilities:

Featurev5v6
Text generationYesYes
StreamingYesYes
Structured outputsYesYes
Tool callingYesYes
Image generationYesYes
Video generationNoYes

Check your installed version with npm list ai. To upgrade, run npm install ai@latest. See the AI SDK v6 migration guide for upgrade details.

The AI SDK uses the AI_GATEWAY_API_KEY environment variable by default. Set it in your .env.local file:

.env.local
AI_GATEWAY_API_KEY=your_ai_gateway_api_key

On Vercel deployments, you can also authenticate with OIDC tokens for keyless authentication.

See Authentication for more details.


Was this helpful?

supported.