Skip to main content
Vercel AI SDK makes it simple to generate text, stream responses, and create structured outputs.

Setup in 3 Steps

1

Install Dependencies

Add the AI SDK and providers:
Terminal
2

Get API Keys

Grab your credentials:OpenAI:
  1. Go to platform.openai.com
  2. Navigate to API keys
  3. Click Create new secret key
Anthropic:
  1. Go to console.anthropic.com
  2. Navigate to API Keys
  3. Click Create Key
Add to .env.local:
.env.local
Never commit API keys to git. Keep them in .env.local only.
3

You're Ready!

All utilities are in /lib/ai.ts and ready to use.
Import and start generating AI content immediately.

Available Models

Choose the right model for your task:
Claude models are faster and cheaper for most tasks. Use GPT-4 for complex reasoning.

Generate Text

Simple Generation

Basic text generation:

Custom Model

Choose a specific model:

API Route Example

app/api/generate/route.ts

Stream Responses

Real-time streaming for chat interfaces:

In API Routes

Perfect for chat applications:
app/api/chat/route.ts
Streaming responses improve UX by showing content as it’s generated, like ChatGPT.

Structured Output

Generate typed objects with Zod schemas:

Complex Schemas

Build sophisticated structured data:
Use structured output for form generation, data extraction, or content creation.

Chat Conversations

Multi-turn conversations with context:

Chat API Route

app/api/chat/route.ts

Edge Runtime

All functions work in Edge Runtime for faster responses:
app/api/generate/route.ts
Edge runtime deploys globally for low-latency AI responses worldwide.

Error Handling

Always handle AI errors gracefully:

Cost Optimization

  • Claude Haiku: Cheapest, fastest (simple tasks)
  • GPT-3.5 Turbo: Affordable, good quality
  • Claude Sonnet: Balanced (recommended)
  • GPT-4: Most expensive (complex reasoning only)
  • Keep prompts concise
  • Use structured output instead of parsing text
  • Stream instead of generating full responses when possible
  • Set lower maxTokens limits

Troubleshooting

Check:
  • Key is in .env.local (not .env)
  • Correct prefix (sk- for OpenAI, sk-ant- for Anthropic)
  • Restart dev server after adding keys
  • No extra spaces in .env.local
Make sure:
  • Using stream.toDataStreamResponse() in API routes
  • Client uses useChat hook from ai/react
  • Not calling .json() on streamed responses
Common issues:
  • Schema too complex (simplify it)
  • Model hallucinating invalid data (add examples)
  • Missing required fields (make them optional)
Solutions:
  • Add retry logic with exponential backoff
  • Implement request queuing
  • Upgrade API tier for higher limits
  • Use Claude (higher rate limits)

Build AI-powered features in minutes 🤖