Vercel AI SDK makes it simple to generate text, stream responses, and create structured outputs.
Setup in 3 Steps
Get API Keys
Grab your credentials:OpenAI:
- Go to platform.openai.com
- Navigate to API keys
- Click Create new secret key
- Go to console.anthropic.com
- Navigate to API Keys
- Click Create Key
.env.local:.env.local
Available Models
Choose the right model for your task: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: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
Choose the right model
Choose the right model
- Claude Haiku: Cheapest, fastest (simple tasks)
- GPT-3.5 Turbo: Affordable, good quality
- Claude Sonnet: Balanced (recommended)
- GPT-4: Most expensive (complex reasoning only)
Reduce token usage
Reduce token usage
- Keep prompts concise
- Use structured output instead of parsing text
- Stream instead of generating full responses when possible
- Set lower
maxTokenslimits
Cache common requests
Cache common requests
Troubleshooting
API key not working?
API key not working?
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
Streaming not working?
Streaming not working?
Make sure:
- Using
stream.toDataStreamResponse()in API routes - Client uses
useChathook fromai/react - Not calling
.json()on streamed responses
Structured output fails?
Structured output fails?
Common issues:
- Schema too complex (simplify it)
- Model hallucinating invalid data (add examples)
- Missing required fields (make them optional)
Rate limit errors?
Rate limit errors?
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 🤖
