AI SDK
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:
npm install aiyarn add aipnpm add aibun add aiGenerate text by passing a plain string model ID. AI Gateway resolves the provider and routes the request automatically.
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:
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:
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:
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:
| Feature | v5 | v6 |
|---|---|---|
| Text generation | Yes | Yes |
| Streaming | Yes | Yes |
| Structured outputs | Yes | Yes |
| Tool calling | Yes | Yes |
| Image generation | Yes | Yes |
| Video generation | No | Yes |
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:
AI_GATEWAY_API_KEY=your_ai_gateway_api_keyOn Vercel deployments, you can also authenticate with OIDC tokens for keyless authentication.
See Authentication for more details.
- Explore the full AI SDK documentation for advanced patterns
- Learn about model routing and fallbacks
- Try other APIs: OpenAI Chat Completions, OpenAI Responses, Anthropic Messages, or OpenResponses
Was this helpful?